简体   繁体   English

在UIView的边界上使用碰撞

[英]Using collision on bounds of UIView

I have an ImageView that moves around the UIView, is it possible to detect collision of the ImageView and the view its self? 我有一个在UIView周围移动的ImageView,是否可以检测到ImageView及其视图自身的碰撞? For example the ImageView hits the side of the view I want it to run an action. 例如,ImageView击中了我希望它执行操作的视图的侧面。 -(void)restart {} If this is possible can you detect which side it has collided with? -(void)restart {}如果可能,您可以检测到它与哪一侧发生了碰撞?

You can create a custom UIImageVIew and implement the methods touchBegan and touchMoved (don't forget to add [self setUserInteractionEnabled:YES] in your init method). 您可以创建一个自定义UIImageVIew并实现touchBegan和touchMoved方法(不要忘记在init方法中添加[self setUserInteractionEnabled:YES] )。 Then set the rect you want to interact with : 然后设置要与之交互的矩形:

customImageView.interactRect = myView.frame;

And in your customImageView you can add something like: 在您的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM