【问题标题】:Using collision on bounds of UIView在 UIView 的边界上使用碰撞
【发布时间】:2015-01-31 20:21:21
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c cocoa-touch uiimageview cgrectintersectsrect


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

    • 这行得通,但我只希望它来自侧面,请你帮忙。
    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2013-04-01
    • 1970-01-01
    相关资源
    最近更新 更多