I recently had the need to use a UIGestureRecognizer for the first time in one of my iOS apps. Specifically, I was interested in recognizing swipe gestures in one of my views so UISwipeGestureRecognizer was the obvious choice.
UISwipeGestureRecognizer is easier to configure than some of the more complicated recognizers since there are only two configurable properties:
numberOfTouchesRequired. I was only interested in single touch swipes, so the default value of
1 was fine for
direction property consists of a bit flag of
UISwipeGestureRecognizerDirection values. My first attempt was to just include the values for left and right gestures:
1 2 3 4
This works fine and swipes in both directions are recognized. The problem comes when it’s time to figure out which direction was swiped in the delegate method:
1 2 3
There is no way to find out which swipe direction triggered the recognizer when the delegate message arrives.
The solution here is straightforward once you realize the problem: you just need to use two recognizers, each configured for a single direction:
1 2 3 4 5 6 7
Now a different method (
swipeLeft) will be called depending on which direction the user swipes. This makes it easy to take the appropriate action in response.