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"@interfaceViewController()@property(nonatomic,strong)UISwipeGestureRecognizer*swipeGestureRecognizer;@end@implementationViewController-(void)viewDidLoad{[superviewDidLoad];/* Instantiate our object */self.swipeGestureRecognizer=[[UISwipeGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleSwipes:)];/* Swipes that are performed from right toleft are to be detected */self.swipeGestureRecognizer.direction=UISwipeGestureRecognizerDirectionLeft;/* Just one finger needed */self.swipeGestureRecognizer.numberOfTouchesRequired=1;/* Add it to the view */[self.viewaddGestureRecognizer: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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access