Saturday, February 13, 2010

Implementing Tap and Hold on the iPhone

In the Apple Developer guide there is some good sample code for implementing the tap and double tap. We've written about that in a previous blog post so won't go over it again here. For something we're doing now, we want to show a little tool palette when the user taps down and holds their finger on the screen. The way we're doing this for now is just to rearrange the code that we use in other applications for tap and double tap.

In the - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event event we call our method to display the palette with a delay of .3. That line looks like this

[self performSelector:@selector(showtheTools:) withObject:buttons[i] afterDelay:0.3];


In our - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event event we first call a cancel of the delay and then perform an action for single tap. The code to cancel the delayed event is

[NSObject cancelPreviousPerformRequestsWithTarget:self];


Our thinking here is that once the tool palette is displayed there is no PerformRequest to cancel so nothing is done. In our touchesEnded even we have one more thing. If the tool palette is displayed, it sets an instance variable. touchesEnded checks that variable and only performs the single tap code if that variable indicates that the palette was not displayed.

UITouch *touch = [touches anyObject];

[NSObject cancelPreviousPerformRequestsWithTarget:self];

if (paletteIsDisplayed == NO) {

if(([touch view] == buttons[i])){

self.touchedButton:buttons[i];

}

}



One of these days, I wish Apple would publish a library of the best practice patterns for handling basic touch gestures. I know that a gesture library is a feature in other O/S and I would love to see it here.

No comments:

Post a Comment