I am looking to implement something in Objective-C for the IOS platform.
I want to have two GUI objects, let\'s just say they are UIImages for simplicity and are square
You can achieve this fairly easily. To the image, you attach a UILongPressGestureRecognizer
and in the action method, you update the image's position based on finger movement. Get the gesture's current location with - (CGPoint)locationInView:(UIView *)
. Upon every movement, you can check whether the image frame overlaps the frame of your target area and if it does, snap it into place.
Checking for overlap is fairly simple (given image and target both are part of the same view hierarchy):
CGRect imageRect = [image convertRect:image.frame toView:[image superview]];
CGRect targetRect = [target convertRect:target.frame toView:[image superview]];
if (CGRectIntersectsRect(imageRect, targetRect)) {
// overlap
}
To move back the image if the user dropped outside, you can make a frame or center animation back to the original position. So, when the drag begins, your action method is called. You check whether your instance variable, let's name it originalCenter, is not equal to CGPointZero
. If it is, you record the current center into originalCenter.
Then, when the user drops the image and it is outsize the target, you move it back:
[UIView animateWithDuration:0.2
animations:^{
image.center = originalCenter;
self.originalCenter = CGPointZero;
}];