Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITapGestureRecognizer - detect double OR triple tap?

I have a case in which 2 completely different behaviors need to take place from a double-tap and a triple-tap on a particular view. I set it up very standard, with the code below:

UITapGestureRecognizer *gestureRecognizerDoubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapDetected:)];
[gestureRecognizerDoubleTap setNumberOfTapsRequired:2];
[self.theView addGestureRecognizer:gestureRecognizerDoubleTap];

UITapGestureRecognizer *gestureRecognizerTripleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tripleTapDetected:)];
[gestureRecognizerTripleTap setNumberOfTapsRequired:3];
[self.theView addGestureRecognizer:gestureRecognizerTripleTap];

The problem I am having is that if a triple-tap is done, the double-tap method is fired as well, since it detects the 2 taps before the 3rd. So upon a triple-tap, both methods are called.

Obviously this isn't an inherent issue with the code or underlying SDK, since it's fully expected. However, I'm curious if anyone has a clever way to somehow prevent the double-tap functionality to be called if a triple-tap is done? I am assuming I may have to set the double-tap functionality on a delayed timer maybe (which would wait a split second to confirm whether a triple-tap is done), but I'm not sure if there's a better way, or even the best way to set this kind of thing up in a clean fashion?

Thanks in advance for any advice you can offer on this!

like image 827
svguerin3 Avatar asked Oct 14 '25 02:10

svguerin3


1 Answers

You can use requireGestureRecognizerToFail: for this problem:

UITapGestureRecognizer *gestureRecognizerTripleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tripleTapDetected:)];
[gestureRecognizerTripleTap setNumberOfTapsRequired:3];
[self.theView addGestureRecognizer:gestureRecognizerTripleTap];

UITapGestureRecognizer *gestureRecognizerDoubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapDetected:)];
[gestureRecognizerDoubleTap requireGestureRecognizerToFail:gestureRecognizerTripleTap];
[gestureRecognizerDoubleTap setNumberOfTapsRequired:2];
[self.theView addGestureRecognizer:gestureRecognizerDoubleTap];

The double-tap one won't fire unless the triple-tap one fails.

The class reference, as usual, has some additional information, and mentions this scenario as a great time to use this method.

like image 196
Aaron Brager Avatar answered Oct 16 '25 22:10

Aaron Brager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!