首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

点击任意区域隐藏键盘

2024-12-18 来源:化拓教育网

#pragma mark - 通过GestureRecognizer实现点击任意区域隐藏键盘

- (void)setKeyBoardAutoHidden{

   NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

   //SingleTap Gesture

   UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapDismissKeyboard:)];

   NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];

   //UIKeyboardWillShowNotification

   [notificationCenter addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {

       [self.view addGestureRecognizer:singleTapGesture];

   }];

   //UIKeyboardWillHideNotification

   [notificationCenter addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQueue usingBlock:^(NSNotification *note) {

       [self.view addGestureRecognizer:singleTapGesture];

   }];

}

- (void) backgroundTapDismissKeyboard:(UIGestureRecognizer *) gestureRecognizer{

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

   [self.view endEditing:YES];

}

显示全文