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

后端 未结 1 1968
走了就别回头了
走了就别回头了 2021-01-31 12:22

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

相关标签:
1条回答
  • 2021-01-31 13:12

    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;
                      }];
    
    0 讨论(0)
提交回复
热议问题