Gesture Recognizers In iOS

In this blog post, we’ll look at the built – in touch gesture recognizers that can be accessed using Interface Builder in Xcode. These gestures include taps, pinches, rotations, swipes, pans, and long presses, which should be sufficient for most developer needs. They are as simple as a control to add to the app, and should be used whenever one of these simple gestures is required in our applications. So, let’s get started.

Start Xcode and create a new app named Gestures using the single view application template. Open the main.storyboard file, and add a label to the view as shown:








Drag a tap gesture recognizer and a swipe gesture recognizer to the view:











Now open up ViewController.h and add two action methods for these recognizers as shown:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

- (IBAction)tapGesture:(UITapGestureRecognizer *)sender;
- (IBAction)swipeGesture:(UISwipeGestureRecognizer *)sender;


Sender in each case is typed to the UIGestureRecognizer subclass we’re interested in. If we had left these typed to “id,” sender would need to be cast to the proper subtype in the method body. This approach is simpler.

Next add the method bodies for these actions to ViewController.m:

- (IBAction)tapGesture:(UITapGestureRecognizer *)sender
    self.view.backgroundColor = [UIColor redColor];

- (IBAction)swipeGesture:(UISwipeGestureRecognizer *)sender
    self.view.backgroundColor = [UIColor greenColor];

In this case, we are simply changing the background color of the main view. The code here can be as simple or complex as needed: we could do virtually anything in response to a touch gesture.

The final step is to wire up these methods to their corresponding recognizers in Interface Builder as shown:


Run the app, then tap the screen. The color changes to red:












Swiping the screen causes the view color to change to green:












If we are adding gesture recognizers to controls that do not normally accept touch gestures (such as image views, for instance), we must make sure to enable user interaction for those controls in the attribute inspector.

Try different combinations of controls and gesture recognizers to see what works. And as always, have fun!


Leave a Comment: