Search code examples
iphoneiosobjective-cuiimageviewibaction

Perform Action When UIImageViews Touch


I want to put two UIImageViews in my app that can be moved. When one image comes in contact with the other, it triggers an action, and then puts both images back in their original places. Any suggestions for this?

I am using

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

UITouch *touch = [touches anyObject];

// If the touch was in the placardView, move the placardView to its location
if ([touch view] == resultImage) {
    CGPoint location = [touch locationInView:self.tabBarController.view];
    resultImage.center = location;

    return;
}
}

This allows resultImage to freely move around. I simply need to know how to detect when any part of it touches the other image (which is stationary) and have that perform an action when it happens, and also return resultImage to its starting location.


Solution

  • Off the top of my head, you can use CGRectContainsPoint four times using the target's frame and the moving image's four corners to see if they touch.

    if(CGRectContainsPoint(collisionTarget.frame, resultImage.frame.origin) ||
       CGRectContainsPoint(collisionTarget.frame, CGPointMake(resultImage.frame.origin.x,resultImage.frame.origin.y+resultImage.frame.size.height)) ||
       CGRectContainsPoint(collisionTarget.frame, CGPointMake(resultImage.frame.origin.x+resultImage.frame.size.width,resultImage.frame.origin.y)) ||
       CGRectContainsPoint(collisionTarget.frame, CGPointMake(resultImage.frame.origin.x+resultImage.frame.size.width,resultImage.frame.origin.y+resultImage.frame.size.height)){
        //do something
    }
    

    EDIT: I completely forgot about CGRectIntersectsRect. You can just use that.

    if(CGRectIntersectsRect(imageView1.frame,imageView2.frame)){
        //do something
    }
    

    Just do the above check in your touchesMoved method right after moving the first image view using the frames of your two image views. Then, restore the first one's position to where it was some point earlier in time. You need to have stored its position in a property or something earlier.