How to detect tap and double tap at same time using UITapGestureRecognizer?

openfrog picture openfrog · Oct 2, 2013 · Viewed 15.5k times · Source

For example I have a view where I want two different gestures:

tap to do action A. double tap to do action B.

The problem is with UITapGestureRecognizer I can only set minimum required tap count. The single tap gesture recognizer recognizes a tap before the double tap gesture recognizer recognizes the double tap.

Example:

_tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognized:)];
_tapGestureRecognizer.numberOfTouchesRequired = 1;
_tapGestureRecognizer.numberOfTapsRequired = 1;
[self addGestureRecognizer:_tapGestureRecognizer];

_doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGestureRecognized:)];
_doubleTapGestureRecognizer.numberOfTouchesRequired = 1;
_doubleTapGestureRecognizer.numberOfTapsRequired = 2;
[self addGestureRecognizer:_doubleTapGestureRecognizer];

It always recognizes the single tap even if I do double tap very fast. How can I set it up so the tap gesture recognizer waits and sees if the double tap gesture recognizer recognizes?

Answer

Adrian P picture Adrian P · Oct 2, 2013

Here is what I have used in one of my old projects, I hope it helps you out man.

UITapGestureRecognizer *singleTap = [[[UITapGestureRecognizer alloc] initWithTarget:    self action:@selector(doSingleTap)] autorelease];
singleTap.numberOfTapsRequired = 1; 
[self.view addGestureRecognizer:singleTap];

 UITapGestureRecognizer *doubleTap = [[[UITapGestureRecognizer alloc] initWithTarget:   self action:@selector(doDoubleTap)] autorelease];
 doubleTap.numberOfTapsRequired = 2; 
 [self.view addGestureRecognizer:doubleTap];

  [singleTap requireGestureRecognizerToFail:doubleTap];