iOS UIGestureRecognizer UITapGestureRecognizer

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Initialize the UITapGestureRecognizer with a target, self in this case, and an action which is a method that has a single parameter: a UITapGestureRecognizer.

After initialization, add it to the view that it should recognize taps in.

Swift

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer = UITapGestureRecognizer(target: self,
                                            action: #selector(handleTap(_:)))
    view.addGestureRecognizer(recognizer)
}

func handleTap(recognizer: UITapGestureRecognizer) {

}

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *recognizer =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(handleTap:)];
    [self.view addGestureRecognizer:recognizer];
}

- (void)handleTap:(UITapGestureRecognizer *)recognizer {

}  


Example of keyboard dismissal through UITapGestureRecognizer:

First, you create the function for dismissing the keyboard:

func dismissKeyboard() {
        view.endEditing(true)
    }  

Then, you add a tap gesture recognizer in your view controller, calling the method we just made

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
        view.addGestureRecognizer(tap)

Example of getting gesture location UITapGestureRecognizer (Swift 3):

func handleTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
if gestureRecognizer.state == UIGestureRecognizerState.recognized
   {
     print(gestureRecognizer.location(in: gestureRecognizer.view))
   }
}


Got any iOS Question?