UITapGestureRecognizer

suggest change

Initialize the UITapGestureRecognizer with a target, self in this case, and an action which is a method that takes the recognizer, or a method with no parameters. The first sample is Swift 2. The keyboard sample uses the older Swift 2 string selector.

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))
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents