Using Touch Handlers in iPhone

Prior to the release of Xcode version 4, managing touch gestures in iOS was done programmatically. Since version 4, we have the ability to create touch handlers directly in Interface Builder. These touch handlers can then be assigned methods like any other active control. So, let’s see how it works!

Start up Xcode, select “Create a new Xcode project,” choose the Single View Application template, and name your project “TouchHandlers.” Use the settings shown below:

Click Next, choose a location to save your project, and click Create.

In the Project Navigator, select the MainStoryboard.storyboard file, which will bring up the storyboard in Interface Builder. Drag a UILabel control from the library to the view, and change the text of the label to “Tap once for red, twice for blue.” Resize and center the label as shown:

Now drag a Tap Gesture Recognizer (UITapGestureRecognizer) from the library to the view. The Tap Gesture Recognizer is located in the library:

Notice that when you drag the tap gesture recognizer to the view, it becomes a child of the view controller rather than the view. We need to create an action method to handle the tap gesture when it occurs.

Since we want to detect not only a single tap, but also a double tap, we will need two tap gesture recognizer objects, so drag another one out now. For the first recognizer, leave all the attributes alone, but for the second, change the Taps attribute to 2 as shown:

Now we’re ready to create the action methods to be executed in response to the tap gestures. Open up the ViewController.h file, and add the bolded in the listing below:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
(IBAction)singleTap:(UITapGestureRecognizer *)sender;
(IBAction)doubleTap:(UITapGestureRecognizer *)sender;
@end

Now open ViewController.m and add the bolded methods shown here:

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
(IBAction)singleTap:(UITapGestureRecognizer *)sender
{
self.view.backgroundColor = [UIColor redColor];
}
(IBAction)doubleTap:(UITapGestureRecognizer *)sender
{
self.view.backgroundColor = [UIColor blueColor];
}
(void)viewDidLoad

All that remains is to wire up the methods to the proper gesture recognizers in Interface Builder. Make sure that singleTap is wired to the recognizer configured for 1 tap and doubleTap is wired to the one configured for 2 taps.

Run the application to test the tap gestures.


There are many other gesture recognizers available in the Interface Builder library. Have fun experimenting will all of them.

Leave a Reply

Your email address will not be published. Required fields are marked *