'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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 halfer
Solution 2