jfisk
jfisk

Reputation: 6225

disable pinch recognizer when 1 finger is lifted on the screen

I have a 2d map that the user can zoom and pan using the gesture recognizers. While it works, i want the user to start panning immediately after a zoom once they have 1 finger lifted. Unfortunately, in the docs it says:

The gesture ends (UIGestureRecognizerStateEnded) when both fingers lift from the view.

which is pretending me from going from a pinch zoom to a pan right away. What could i do to fix this?

Upvotes: 2

Views: 1897

Answers (2)

Raghuraman
Raghuraman

Reputation: 1

Use this code inside the gesture handling method.

if (gesture.numberOfTouches != 2) { // code here to end pinching }

As Gesture handling method will be called immediately when user lift a finger while 2 finger pinching.

Upvotes: 0

NJones
NJones

Reputation: 27147

This is possible, and easy! It involves being your gesture recognizer's delegate. Something no-one seems to know exists. In my view controller subclass I have declared both conforming to the protocol <UIGestureRecognizerDelegate> and two ivars:

UIPinchGestureRecognizer *myPinchGR;
UIPanGestureRecognizer *myPanGR;

These ivars are instantiated in view did load. Notice setting self as the delegate.

-(void)viewDidLoad{
    [super viewDidLoad];
    myPanGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panTarget:)];
    myPanGR.delegate = self;
    [self.view addGestureRecognizer:myPanGR];

    myPinchGR = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchTarget:)];
    myPinchGR.delegate = self;
    [self.view addGestureRecognizer:myPinchGR];
}

One of the delegate calls made by a UIGestureRecognizer is shouldRecognizeSimultaneouslyWithGestureRecognizer: if I had more than two gesture recognizers then this function would have to contain some logic. But since there are only two I can just return YES.

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

Now you do have to include a little (very little) extra logic in your action methods to screen for the appropriate conditions.

-(void)panTarget:(UIPanGestureRecognizer *)panGR{
    if (panGR.numberOfTouches > 1) return;
    NSLog(@"panny");
}
-(void)pinchTarget:(UIPinchGestureRecognizer *)pinchGR{
    if (pinchGR.numberOfTouches < 2) return;
    NSLog(@"pinchy");
}

Run this code an look at the logs. you will see when you move one finger you will see "panny" when you place a second finger down you will see "pinchy", and back and forth.

Upvotes: 5

Related Questions