Search code examples
objective-cioscocoa-touch

Detecting the direction of PAN gesture in iOS


In my app there is a image view.Im adding PAN gesture to that image view.

This is working fine.

The image view is in landscape mode.

I want to increase a count in label while user pan to right direction and decrease that count while user pan to left direction.

I googled a lot but didn't find a solution for this.

Can anyone please help me how to detect the direction in which the user is panning(left/right)?


Solution

  • In the target selector of your gesture recognizer, use - (CGPoint)velocityInView:(UIView *)view;:

    - (void)panRecognized:(UIPanGestureRecognizer *)rec
    {
        CGPoint vel = [rec velocityInView:self.view];
        if (vel.x > 0)
        {
            // user dragged towards the right
            counter++;
        }
        else
        {
            // user dragged towards the left
            counter--;
        }
    }
    

    P.s.: I didn't know about this method until approx. 3 minutes before. One of Google's first hits was the official Apple documentation.