I want to detect JUST double / single tap when the user touches a view.
I made something like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint prevLoc = [touch ]
if(touch.tapCount == 2)
NSLog(@"tapCount 2");
else if(touch.tapCount == 1)
NSLog(@"tapCount 1");
}
But it always detect 1 tap before 2 taps. How can I detect just 1 / 2 tap?
Thanks for you help. I also found a way like that:
-(void)handleSingleTap
{
NSLog(@"tapCount 1");
}
-(void)handleDoubleTap
{
NSLog(@"tapCount 2");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSUInteger numTaps = [[touches anyObject] tapCount];
float delay = 0.2;
if (numTaps < 2)
{
[self performSelector:@selector(handleSingleTap) withObject:nil afterDelay:delay ];
[self.nextResponder touchesEnded:touches withEvent:event];
}
else if(numTaps == 2)
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[self performSelector:@selector(handleDoubleTap) withObject:nil afterDelay:delay ];
}
}
It will help to define methods for single and double taps
(void) handleSingleTap {}
(void) handleDoubleTap {}
So then in touchesEnded
you can call the appropriate method based on the number of taps, but only call handleSingleTap after a delay to make sure double tap has not been executed:
-(void) touchesEnded(NSSet *)touches withEvent:(UIEvent *)event {
if ([touch tapCount] == 1) {
[self performSelector:@selector(handleSingleTap) withObject:nil
afterDelay:0.3]; //delay of 0.3 seconds
} else if([touch tapCount] == 2) {
[self handleDoubleTap];
}
}
In touchesBegan
, cancel all requests to handleSingleTap so that the second tap cancels the first tap's call to handleSingleTap
and only handleDoubleTap
will be called
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(handleSingleTap) object:nil];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With