Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect only double or single tap with UIViews?

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?

like image 313
trung nguyen Avatar asked Feb 28 '11 10:02

trung nguyen


2 Answers

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 ];
    }               
}
like image 105
trung nguyen Avatar answered Sep 30 '22 15:09

trung nguyen


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];
like image 40
dianovich Avatar answered Sep 30 '22 15:09

dianovich