首页 > 代码库 > iOS点击空白区域隐藏键盘

iOS点击空白区域隐藏键盘

- (void)setupForDismissKeyboard

{

  NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

  UITapGestureRecognizer *singleTagGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnyWhereToDismissKeyboard:)];

  __weak UIViewController *weakSelf = self;

  NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];

  [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note){[weakSelf.view addGestureRecognizer:singleTapGR];}];

  [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note){[weakSelf.view removeGestureRecognizer:singleTapGR];}];    

}

 

- (void)tapAnyWhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer

{

  //此method 会将self.view里所有的subview的first responder 都resign掉

  [self.view endEditing:YES];

  [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillHideNotification object:nil];

}

iOS点击空白区域隐藏键盘