Detecting Taps

So far, this chapter has focused on the conceptual side of Multi-Touch programming. The remainder of the chapter will focus on example code showing how to detect and use the main types of touch sequence.

Detecting Single Taps

Single taps are used by standard buttons, links (in browsers and the SMS application), and many other UIControl subclasses. They are also used by the iPhone OS to launch applications. Users touch elements on the screen to communicate intent and, in doing so, expect a response. On the Home screen, the response is to launch an application. With buttons, a specific action is usually expected: search, close, cancel, clear, accept.

Single taps are trivial to detect. The simplest method is to assign an action to a UIControl subclass (versus a custom UIView subclass). This sends a specific message to a given object. For a given UIControl, send the addTarget:action:forControlEvents: message with appropriate parameters to assign a receiving target and action message for any number of control events. This example assumes a UIButton instance in a UIView subclass with the instance variable name button:

- (void) awakeFromNib
{
	[super awakeFromNib];
	[button addTarget:self action:@selector(handleButtonPress:)
		forControlEvents:UIControlEventTouchDown];
}

- (IBAction) handleButtonPress:(id)sender
{
	NSLog(@"Button pressed!");
}

For responder objects that are not descendants of UIControl, you can detect single taps within the touchesBegan:withEvent: handler:

- (void) ...

Get Programming the iPhone User Experience now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.