0

我有一个围绕 UIView 移动的 ImageView,是否可以检测到 ImageView 和视图自身的碰撞?例如 ImageView 击中视图的一侧,我希望它运行一个动作。-(void)restart {} 如果这是可能的,您能否检测到它与哪一侧发生碰撞?

4

1 回答 1

0

您可以创建自定义 UIImageVIew 并实现方法 touchBegan 和 touchMoved(不要忘记添加[self setUserInteractionEnabled:YES]init 方法)。然后设置要与之交互的矩形:

customImageView.interactRect = myView.frame;

在您的 customImageView 中,您可以添加如下内容:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    lastPosition = [touch locationInView: self.superview];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint position = [touch locationInView:self.superview];
    CGRect currentFrame = self.frame;
    currentFrame.origin = CGPointMake(currentFrame.origin.x + position.x - lastPosition.x, currentFrame.origin.y + position.y - lastPosition.y);

    if (CGRectIntersectsRect(currentFrame, interactRect) && !CGRectIntersectsRect(self.frame, interactRect))
    {
        NSLog(@"I'm in for the first time");
        if(self.frame.origin.x + self.frame.size.width <= interactRect.origin.x &&    currentFrame.origin.x + currentFrame.size.width > interactRect.origin.x)
        {
            NSLog(@"Coming from the left");
        }
        if(self.frame.origin.x >= interactRect.origin.x + interactRect.size.width && currentFrame.origin.x < interactRect.origin.x + interactRect.size.width)
        {
            NSLog(@"Coming from the right");
        }
    }
    self.frame = currentFrame;
    lastPosition = position;
}
于 2014-12-03T10:54:54.710 回答