How can I dismiss the keyboard if a user taps off the on-screen keyboard?

The simplest solution I have used is this:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

      [self.view endEditing:YES];

}

The endEditing command can be used on any view that contains your textfield as a subview. The other advantage of this method is that you don't need to know which textfield triggered the keyboard. So even if you have a multiple textfields, just add this line to the superview.

Based on the Apple documentation, I think this method exists specifically to solve this problem.


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

The code:

In viewDidLoad

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

[self.view addGestureRecognizer:tap];

In dismissKeyboard:

-(void)dismissKeyboard {
       [aTextField resignFirstResponder];
}

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

OPTION 2

If you can't afford to add a gestureRecognizer then you can try this

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * touch = [touches anyObject];
    if(touch.phase == UITouchPhaseBegan) {
        [aTextField resignFirstResponder];
    }
}