O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.1. Detecting Swipe Gestures

Problem

You want to be able to detect when the user performs a swipe gesture on a view—for instance, swiping a picture out of the window.

Solution

Instantiate an object of type UISwipeGestureRecognizer and add it to an instance of UIView:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong)
    UISwipeGestureRecognizer *swipeGestureRecognizer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /* Instantiate our object */
    self.swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(handleSwipes:)];
    
    /* Swipes that are performed from right to
     left are to be detected */
    self.swipeGestureRecognizer.direction =
    UISwipeGestureRecognizerDirectionLeft;
    
    /* Just one finger needed */
    self.swipeGestureRecognizer.numberOfTouchesRequired = 1;
    
    /* Add it to the view */
    [self.view addGestureRecognizer:self.swipeGestureRecognizer];
    
}

A gesture recognizer could be created as a standalone object, but here, because we are using it for just one view, we have created it as a property of the view controller that will receive the gesture (self.swipeGestureRecognizer). This recipe’s Discussion shows the handleSwipes: method used in this code as the target for the swipe gesture recognizer.

Discussion

The swipe gesture is one of the most straightforward motions that built-in iOS SDK gesture recognizers will register. It is a simple movement of one or more fingers on a view from one direction ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required