Dismiss a keyboard with tap on view

suggest change

To hide the keyboard when the user taps outside a text field, add a tap recognizer that calls endEditing. cancelsTouchesInView = NO lets the tap reach controls under the recognizer.

- (void)viewDidLoad {
    [super viewDidLoad];

    // dismiss keyboard when tap outside a text field
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self.view action:@selector(endEditing:)];
    [tapGestureRecognizer setCancelsTouchesInView:NO];
    [self.view addGestureRecognizer:tapGestureRecognizer];
}

The same gesture in Swift. dismissKeyboard must be exposed to Objective-C, and YourVCName is this view controller:

override func viewDidLoad() {
    super.viewDidLoad()

    // dismiss keyboard when tap outside a text field 
    let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourVCName.dismissKeyboard))
    view.addGestureRecognizer(tapGestureRecognizer)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

Another Swift 3 example. txtSomeField is the text field. touchesBegan has to live on the class. A method cannot be overridden in an extension.

class vc: UIViewController, UITextFieldDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        txtSomeField.delegate = self
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}

Feedback about page:

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



Table Of Contents