UIGestureRecognizer dependencies

Goran on

xcode_1title

Common sense for gestures detection in iOS programming is to use UIGestureRecognizer class. Gestures you can detect are: tap, pinch, rotation, swipe, pan and long press. To define gesture recognizer you’ll have to use one of UIGestureRecognizer subclasses:

  • UITapGestureRecognizer;
  • UIPinchGestureRecognizer;
  • UIRotationGestureRecognizer;
  • UISwipeGestureRecognizer;
  • UIPanGestureRecognizer;
  • UILongPressGestureRecognizer.

It’s possible to create dependencies between gesture recognizers and I’ll show you how to do it on example with tap gestures. We need dependencies in case we want some recognizer to fail if other recognizer occurs, e.g. single tap action will be canceled if double tap occurs.

Start new view based project and in viewDidLoad method define three gesture recognizer as follows. After you define gesture recognizers for single, double and triple tap define dependencies using requireGestureRecognizerToFail method. This method will delay first recognizer to see will next one occur. Single tap waits to see will double tap occur, double tap will wait to see will triple tap occur. After you add gestures to view release them, define actions tap, doubleTap and tripleTap.

// define single tap gesture recognizer
 UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer
 alloc] initWithTarget:self action:@selector(tap:)];
 singleTap.numberOfTapsRequired = 1;
// define double tap gesture recognizer
 UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer
 alloc] initWithTarget:self action:@selector(doubleTap:)];
 doubleTap.numberOfTapsRequired = 2;
// define triple tap gesture recognizer
 UITapGestureRecognizer *tripleTap = [[UITapGestureRecognizer
 alloc] initWithTarget:self action:@selector(tripleTap:)];
 tripleTap.numberOfTapsRequired = 3;
// single tap will fail if double tap occurs
 [singleTap requireGestureRecognizerToFail: doubleTap];
 // dobule tap will fail if triple tap occurs
 [doubleTap requireGestureRecognizerToFail: tripleTap];
// add gesture recognizers to view
 [self.view addGestureRecognizer:singleTap];
 [self.view addGestureRecognizer:doubleTap];
 [self.view addGestureRecognizer:tripleTap];
// release gesture recognizers
 [singleTap release];
 [doubleTap release];
 [tripleTap release];

In case you want to copy/paste actions, here they are:

- (void)tap:(id)sender {
 NSLog (@"sinle tap");
 }
- (void)doubleTap:(id)sender {
 NSLog (@"double tap");
 }
- (void)tripleTap:(id)sender {
 NSLog (@"triple tap");
 }

Run project and start console, as you click once on view in Console window you’ll see message “single tap”, as you click twice message “double tap” will appear since double tap canceled single tap action. Triple tap will cancel single and double tap action, so message “triple tap” will appear.
Thanks for reading!

Leave Your Comment

You’re more than welcome to leave your own comment!

Just please, pretty please: don’t spam. Thank you :)