How to restrict a moveable view by Pan gesture

StuartM picture StuartM · Jul 23, 2013 · Viewed 17k times · Source

I have a UIImageView which is moveable via a pan gesture.

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self.photoMask addGestureRecognizer:pan];

I would like to restrict the area this can be moved on screen. Rather than the user be able to drag the view right to the side of the screen, I want to restrict it by a margin of some sort. How can I do this?

Also, how is this then handled when rotated?

EDIT ---

#pragma mark - Gesture Recognizer
-(void)handlePan:(UIPanGestureRecognizer *)gesture {
    NSLog(@"Pan Gesture");
    gesture.view.center = [gesture locationInView:self.view];
}

This is my current method to handle the pan. What I need to do is continue to move the imageview by the center point and also restrict its movement when close to the edge of the screen by 50 for example.

Answer

Chris Tetreault picture Chris Tetreault · Jul 24, 2013

One possible solution to this is in your handlePan method, check the location of the point on the screen, and only commit the change if it is within the bounds you wish to restrict it to.

For ex.

-(void) handlePan:(UIGestureRecognizer*)panGes{

    CGPoint point = [panGes locationInView:self.view];

    //Only allow movement up to within 100 pixels of the right bound of the screen
    if (point.x < [UIScreen mainScreen].bounds.size.width - 100) {

        CGRect newframe = CGRectMake(point.x, point.y, theImageView.frame.size.width, theImageView.frame.size.height);

        theImageView.frame = newframe;

    }

}

I believe this would also correctly handle any screen rotation

EDIT

To move your image view by the center of its frame, the handlePan method could look something like this.

-(void)handlePan:(UIPanGestureRecognizer *)gesture {

    CGPoint point = [gesture locationInView:self.view];

    //Only allow movement up to within 50 pixels of the bounds of the screen
    //Ex. (IPhone 5)
    CGRect boundsRect = CGRectMake(50, 50, 220, 448);

    if (CGRectContainsPoint(boundsRect, point)) {
        imgView.center = point;
    }       
}

Check whether the point is within your desired bounds, and if so, set the center of your image view frame to that point.