Thursday, October 2, 2008

Handling Double Taps

Alright, since the NDA is down, let's celebrate by posting some information, shall we?

One question that I see posted a lot by new iPhone developers is "how do I handle double-taps?" The problem is that a double tap calls touchesBegan:withEvent: twice. If you want to have a different method called for a single-tap then a double-tap (in other words, if there's a double-tap, you don't want the single-tap method to fire), how do you handle it?

The answer lies in first using performSelector:withObject:afterDelay: to call the single-tap method after a delay that's short enough not to be noticed by the user, but long enough that the second tap of the double-tap will arrive before it actually executes. Then when the double-tap comes into touchesBegan:withEvent:, you use a little-known NSObject method called cancelPreviousPerformRequestsWithTarget:selector:object: to cancel the previous single-tap method call before calling the double-tap method.

Heres a code snippet that shows how to handle up to a quadruple-tap, with each number of taps resulting in a different method getting called.


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
NSUInteger tapCount = [touch tapCount];

switch (tapCount) {
case 1:
[self performSelector:@selector(singleTapMethod) withObject:nil afterDelay:.4];
break;
case 2:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTapMethod) object:nil];
[self performSelector:@selector(doubleTapMethod) withObject:nil afterDelay:.4];
break;
case 3:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doubleTapMethod) object:nil];
[self performSelector:@selector(tripleTapMethod) withObject:nil afterDelay:.4];
break;
case 4:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tripleTapMethod) object:nil];
[self quadrupleTap];
break;
default:
break;
}

}
@end

No comments:

Post a Comment