IOS click anywhere to exit the keyboard

Application scenarios: login interface or fill in the information when you click the blank exit keyboard

  • The general solution:
    1 scrollView real-time monitoring agency rolling method called the [self.view endEditing:YES] or [self.textField resignFirstResponse];
    2.touchBegin method, called [self.view endEditing:YES] or [self.textField resignFirstResponse];

Here is another solution

  • 1 write a classification for viewController
  • 2 use the keyboard to eject and exit the notification call the corresponding method
  • 3 add a click gesture to the current controller
@interface UIViewController (DismissKeyboard) - (void) setupForDismissKeyboard; @end
@implementation UIViewController (DismissKeyboard) - (void) setupForDismissKeyboard NSNotificationCenter [NSNotificationCenter defaultCenter] {*nc = UITapGestureRecognizer; *singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector (tapAnywhereToDismissKeyboard:)]; __weak UIViewController *weakSelf = self NSOperationQueue *mainQuene; =[NSOperationQueue mainQueue]; [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^ (NSNotification *note) {[weakSelf.view addGestureRecognizer:singleTapGR]; [nc addObserverForNam}]; E:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^ (NSNotification *note) {[weakSelf.view removeGestureRecognizer:singleTapGR];} -}]; (void) tapAnywhereToDismissKeyboard: (UIGestureRecognizer * gestureRecognizer) {/ / the method will self.view first responder all subview resign off [self.view endEditing:YES];}


  • 1 import header file
#import "UIViewController+DismissKeyboard.h"
  • 2 active calls in the viewDidLoad method
- (void) viewDidLoad {[super viewDidLoad]; [self setupForDismissKeyboard];}