10.5. Detecting Tap Gestures
Problem
You want to be able to detect when users tap on a view.
Solution
Create an instance of the UITapGestureRecognizer class and add it to the
target view, using the addGestureRecognizer: instance method of the
UIView class. Let’s have a look at
the definition of the view controller:
#import "ViewController.h"@interfaceViewController()@property(nonatomic,strong)UITapGestureRecognizer*tapGestureRecognizer;@end@implementationViewController
The implementation of the viewDidLoad instance method of the view
controller is as follows:
-(void)viewDidLoad{[superviewDidLoad];/* Create the Tap Gesture Recognizer */self.tapGestureRecognizer=[[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(handleTaps:)];/* The number of fingers that must be on the screen */self.tapGestureRecognizer.numberOfTouchesRequired=2;/* The total number of taps to be performed before thegesture is recognized */self.tapGestureRecognizer.numberOfTapsRequired=3;/* Add this gesture recognizer to our view */[self.viewaddGestureRecognizer:self.tapGestureRecognizer];}
Discussion
The tap gesture recognizer is the best candidate among gesture recognizers to detect plain tap gestures. A tap event is the event triggered by the user touching and lifting his finger(s) off the screen. A tap gesture is a discrete gesture.
The locationInView: method
of the UITapGestureRecognizer class can be used to detect the location of the tap event. If the tap gesture requires ...
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