user3007080
user3007080

Reputation: 335

Dismiss Keyboard

So I have a self created top bar controller that is being implemented in my other controllers views. I have a textfield on this top bar. I was wondering what the best approach to having the keyboard dismiss if the user clicks anywere outside the keyboard. I do have a tap gesture recognizer that performs the method dismisskeyboard. However, this only works if the user clicks on the top bar outside the keyboard. Is there a way to set it up so if the user clicks anywere on the screen, then this will dismiss the keyboard?

Upvotes: 1

Views: 164

Answers (2)

Ayan Sengupta
Ayan Sengupta

Reputation: 5396

The approach I would describe is a hack but still works.

  1. create a transparent UIButton with the frame of the view, like below:

    UIButton* overlay = [UIButton buttonWithType:UIButtonTypeCustom];
    overlay.frame = self.view.bounds;
    overlay.backgroundColor = [UIColor clearColor];
    [overlay addTarget:self action:@selector(hideOverlay:) forControlEvents:UIControlEventTouchDown];
    [self.view.subviews[0] insertSubview:overlay belowSubview:self.textField];
    
  2. Create a method hideOverlay to dismiss the keyboard and hide the transparent:

    -(void)hideOverlay:(id)sender {
        UIView* overlay = sender;
        [overlay removeFromSuperview];
        [self.textField resignFirstResponder];
    }
    

You should ideally call the first block of code in textFieldDidBeginEditing: protocol method of UITextFieldDelegate and you should register your calling class accordingly.

Upvotes: 1

David Berry
David Berry

Reputation: 41246

You might try giving the text field a transparent inputAccessoryView, sized to fill the rest of the screen, that catches taps and dismisses the keyboard.

Upvotes: 1

Related Questions