Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to program drag and drop with snap to area in Objective-C for IOS

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 shapes.

And then I have an "empty" GUI element that is just a greyed out square of the same size.

I want the user to be able to drag one of the square images over to the empty square and as long as some part of the image is touching the empty square it will snap into that empty square and fill it up. And if they drop the image anywhere else it animates back to the original location.

As well I would want to have 2 other square images and another empty square such with the same interaction but each group of 2 images and 1 empty square can't work between each other. i.e. the first two images can only be dropped into the first empty square.

I assume there would be some drop event I am looking to capture and then determine if the image meta data matches with the empty square it is being dropped into.

If you know of any code samples or apps out there I can certainly work through the code to understand or if you have some objects, events and properties to point me to that would be great.

This isn't for a game as much as an app so I would prefer not to work in any of the game engines but if that is an easy way to do it then I am all for that.

like image 257
user461051 Avatar asked Feb 10 '12 18:02

user461051


1 Answers

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;
                  }];
like image 70
Pascal Avatar answered Nov 11 '22 20:11

Pascal