O'Reilly logo

iOS 5 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

7.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:

- (void)viewDidLoad {
  [super viewDidLoad];
  
  /* Instantiate the 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];
  
}

- (void) viewDidUnload{
  [super viewDidUnload]; 
  self.swipeGestureRecognizer = nil;
}

A gesture recognizer could be created as a standalone object, but here, because we are using it just for 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 to another. The UISwipeGestureRecognizer, like other gesture recognizers, inherits from ...

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