Tuesday, December 30, 2008

iphone : how to differentiate single & multiple taps

Aim: 

Make single tapping and double tapping on iphone trigger different event handling functions respectively.

Difficulty:  

When you double tap, the first tap will be recognized as single tapping and trigger the single tapping handling function. 
After that, the second tapping will be recognized as double tapping and trigger the double tapping handling function.

So if you rewrite touchesEnd as follows:

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

switch ([touch tapCount])
{
case 1:
[self singleTapHandlingFunction];
break;
case 2:
[self doubleTapHandlingFunction];
break;
}

}

If you double tap, both singleTapHandlingFunction and doubleTapHandlingFunction are triggered, which in most cases not desirable.

How to solve:
"iPhone OS Programming Guide 2.0"
 page 145 has provided a solution:

1. In touchesEnded:withEvent:, when the tap count is one, the responder object sends itself a performSelector:withObject:afterDelay: message. The selector identifies another method implemented by the responder to handle the single-tap gesture; the object for the second parameter is the related UITouch object; the delay is some reasonable interval between a single- and a double-tap gesture.

2. In touchesBegan:withEvent:, if the tap count is two, the responder object cancels the pending delayed-perform invocation by sending itself a CancelPreviousPerformRequestsWithTarget: message. If the tap count is not two, the method identified by the selector in the previous step for single-tap gestures is invoked after the delay.

3. In touchesEnded:withEvent:, if the tap count is two, the responder performs the actions necessary for handling double-tap gestures.

An example code is provided in the following thread:

No comments:

Post a Comment