点击除了TextField的任何位置收键盘

点击空白和任意控件收键盘,第一次用.

    

- (void)viewDidLoad
{
    [super viewDidLoad];
  
  [self setUpForDismissKeyboard];
}
- (void)setUpForDismissKeyboard {  NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  UITapGestureRecognizer *singleTapGR =
  [[UITapGestureRecognizer alloc] initWithTarget:self
                                          action:@selector(tapAnywhereToDismissKeyboard:)];
  NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
  [nc addObserverForName:UIKeyboardWillShowNotification
                  object:nil
                   queue:mainQuene
              usingBlock:^(NSNotification *note){
                [self.view addGestureRecognizer:singleTapGR];
              }];
  [nc addObserverForName:UIKeyboardWillHideNotification
                  object:nil
                   queue:mainQuene
              usingBlock:^(NSNotification *note){
                [self.view removeGestureRecognizer:singleTapGR];
              }];
}
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer{
//此method会将self.view里所有的subview的first responder都resign掉
  [self.view endEditing:YES];
}

本文转帖,来源已注明.

你可能感兴趣的:(收键盘)