IOS 简单的单击屏幕键盘返回手势

388 阅读1分钟

根据系统键盘通知,添加或移除单击停止编辑的手势

在iOS开发中总是会碰到键盘回收的问题,这个方法可以添加在BaseViewController或是ViewController的category中

- (void)addAutoDismissKeyboardGesture {
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(autoDismissKeyboardGestureAction:)];
    NSOperationQueue *mainQuene = [NSOperationQueue mainQueue];
    // add Gesture
    [notificationCenter addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){
        [self.view addGestureRecognizer:singleTapGesture];
    }];
    // remove Gesture
    [notificationCenter addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){
        [self.view removeGestureRecognizer:singleTapGesture];
    }];
}

- (void)autoDismissKeyboardGestureAction:(UIGestureRecognizer *)gestureRecognizer {
    [self.view endEditing:YES];
}