Sheehan Alam Sheehan Alam - 1 year ago 77
iOS Question

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

I want to be able to dismiss the iPhone keyboard when the user taps anywhere outside of the keyboard. How can I go about doing this? I know I need to dismiss the responder, but need to know how to implement it when a user taps out of the keyboard space.

Answer Source

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

[self.view addGestureRecognizer:tap];

In dismissKeyboard:

-(void)dismissKeyboard {
       [aTextField resignFirstResponder];

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


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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download