UISwipeGestureRecognizer with touchesEnded

Target: iOS
Situation: You have a UIView and it’s set up in your storyboard to detect a swipe gesture (let’s say a direction of right) and it calls a selector in your viewController. You’d like a user to be able to swipe to the right and hold their finger in position and repeatedly call a method (say for scrolling). You need the gesture recognizer to work but you also need to implement touchesEnded in order to kill the NSTimer that’s being used.

A Solution:Set up an IBOutlet for the UISwipeGestureRecognizer. In your viewDidLoad set the following:

swipeRight.cancelsTouchesInView = NO;
swipeRight.delaysTouchesBegan   = NO;
swipeRight.delaysTouchesEnded   = NO;

These are important. The default behavior of a gesture recognizer is to avoid having both it and the view process the touch. So that needs to be fine-tuned. The code above allows for this.

Now the selector (method) is called – whichever you’d like when the gesture is recognized (you set this up in your storyboard – or in code too if you’d like). When that method is fired, you know the direction and you start your NSTimer – to get the repeat effect. When touchesEnded is called in your viewController you can kill that NSTimer (invalidate it) and that’s it. You could use variable flags to determine which timer was being used, etc. if you’d like (different directions).

So you end up with a swipe to the right & hold method that will repeatedly do “something” for the user. A release stops that repetition for the user. Over time you could also change the delay for the timer and have it speed up if “held” long enough.

Pretty cool.

Related Posts Plugin for WordPress, Blogger...

Leave a Reply

Your email address will not be published. Required fields are marked *


− one = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>