8.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
];
}
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 the UIGestureRecognizer
class and adds various functionalities to this class, ...
Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.