Wingzero Wingzero - 1 year ago 88
iOS Question

How to filter a quick multiple tap for single Tap event and double tap event

I have below gestures setup:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
singleTap.numberOfTapsRequired = 1;
[self addGestureRecognizer:singleTap];

UITapGestureRecognizer *doubleClick = [[UITapGestureRecognizer alloc] initWithTarget:self
doubleClick.numberOfTapsRequired = 2;
[self addGestureRecognizer:doubleClick];

[singleTap requireGestureRecognizerToFail:doubleClick];

When I quickly tap 3 times, I find that it will be translated into one double tap event and one single tap event, and introduce a bug for my app.

I want something like if user clicks 3 or more times, only a double tap event will be triggered. Could some one help on this? Thank in advance.

Answer Source

You can use the gesture recognizer's delegate to temporarily disable both gestures after a double click. The code below disables the gestures for 0.6 seconds after a double click.

You'll need a couple properties

@property int disableGestures;
@property CFTimeInterval timeStamp;

and some additional initialization

self.disableGestures = NO;
singleTap.delegate = self;
doubleClick.delegate = self;

and you'll need to conform to the <UIGestureRecognizerDelegate> protocol, and implement the shouldReceiveTouch method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
    if ( self.disableGestures )
        if ( CACurrentMediaTime() - self.timeStamp < 0.6 )
            return NO;
        self.disableGestures = NO;
    return YES;

All that's left is to disable the gestures after a double click

- (void)doubleClickDetected:(UITapGestureRecognizer *)gesture
    self.disableGestures = YES;
    self.timeStamp = CACurrentMediaTime();

    // normal processing for the double click goes here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download