Using collision on bounds of UIView

123 Views Asked by At

I have an ImageView that moves around the UIView, is it possible to detect collision of the ImageView and the view its self? For example the ImageView hits the side of the view I want it to run an action. -(void)restart {} If this is possible can you detect which side it has collided with?

1

There are 1 best solutions below

1
On BEST ANSWER

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). Then set the rect you want to interact with :

customImageView.interactRect = myView.frame;

And in your customImageView you can add something like:

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