IOS – Dismiss keyboard when touching outside of UITextField


I'm wondering how to make the keyboard disappear when the user touches outside of a UITextField.

Best Solution

You'll need to add an UITapGestureRecogniser and assign it to the view, and then call resign first responder on the UITextField on it's selector.

The code:

In viewDidLoad

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];

[self.view addGestureRecognizer:tap];

In dismissKeyboard:

    [aTextField resignFirstResponder];

(Where aTextField is the textfield that is responsible for the keyboard)

Swift 3 version looks like that

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))

For dismissKeyboard

@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {