Search code examples
gestures

How to Stop Single Tap From firing before Double Tap


I am trying to set a simple double tap recognition before moving to more complicated interactions. I have the single and double tap being recognised. However, my problem is that the double tap doesn't fire without the single tap.

I have seen the code which covers introducing a requirement to fail, but the sample code I do not understand how to modify to make work with my standard approach.

Here is my code - at the moment I am just trying to get the log to fire and it is. But on double tap I get the single tap message which I don't want. I have tried changing the TapGestureRecognizer event settings to no avail.

- (IBAction)didTapPhoto1:(UITapGestureRecognizer *)sender; {


NSLog(@"Did Tap Photo1 !");

}



- (IBAction)didDoubleTapPhoto1:(UITapGestureRecognizer *)sender; {


    NSLog(@"DoubleTap");
}

Thank you


Solution

  • Use UIGestureRecognizer requireGestureRecognizerToFail: method.

    [singleTapGestureRecognizer requireGestureRecognizerToFail:doubleTapGestureRecognizer].

    There is a side effect of this method, if you only tap one time on the screen, it will react slower than that without calling the method.

    Edit: It seems that you create the gesture recognizer in Storyboard or xib. You can also do it with code.

    UITapGestureRecognizer *singleGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapPhoto1:)] ;
    singleGR.numberOfTapsRequired = 1 ;
    UITapGestureRecognizer *doubleGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didDoubleTapPhoto1:)] ;
    doubleGR.numberOfTapsRequired = 2 ;
    // you can change self.view to any view in the hierarchy.
    [self.view addGestureRecognizer:singleGR] ;
    [self.view addGestureRecognizer:doubleGR] ;
    
    [singleGR requireGestureRecognizerToFail:doubleGR] ;