Last Updated: July 04, 2017
· d2burke

iOS: Handling Pan Gestures Properly

Using Pan Gesture recognizers in your iOS app makes for a fun and convenient experience. You may find that you want to assign a gesture to a specific view and move that view around, such as an image for drag and drop or the header of some content view.

In these cases it makes sense to move the view around by the change in position of the touch as the user moves their finger around. One thing to keep in mind is that the touch point and occur anywhere in that view, soooo...you'll want to account for the offset of the touch point in that view as you calculate where to move it. Take a look at the code below for an easy way to do this:

//In your header file, make sure to create a reference to your initial
//touch point for later reference
@property (strong, nonatomic) CGFloat touchPositionInHeaderY;

//In your implementation file (.m)
CGFloat y = [gestureRecognizer locationInView:self.view].y;

if(gestureRecognizer.state == UIGestureRecognizerStateBegan){
    //Snag the Y position of the touch when panning begins
    _touchPositionInHeaderY = [gestureRecognizer locationInView:_menuHeaderView].y;
else if(gestureRecognizer.state == UIGestureRecognizerStateChanged){
    //This represents the true offset with the touch position accounted for
    CGFloat trueOffset = y - _touchPositionInHeaderY;

    //Use this offset to adjust the position of your view accordingly
    menuFrame.origin.y = trueOffset;
    _menuView.frame = menuFrame;

So, if you touch at the top of the header view (if that's what you want to pan around) this code makes sure there's no glitchy "jump" as would occur if you were simply assigning the origin.y of the panned view to the actual offset.y of the touch.

It's easy to start an iOS app, but it's rather difficult to finish one with the polish expected of iOS users. Go forth make smooth things.

Say Thanks

2 Responses
Add your response


Property with 'retain' (or strong) must be of object type

over 1 year ago ·

I'm new to Obj C and iOS environment, what I don't understand here is that, what are _menuView,menuFrame and their relation to _menuHeaderView. I just have 2 UIimageViews, view1 which is subview of view2 which in turn is subview of self.view and I want to pan view1 on view2. I'm not able to relate the views mentioned in the example above to my views properly. Any help is appreciated.

Thanks in advance.

8 months ago ·