iOS 结束当前界面编辑(隐藏键盘)

两种比较好的方式:

方式一: 监听通知 UITextFieldTextDidBeginEditingNotification
#pragma mark - <控制器生命周期>
- (void)viewDidLoad {
    [super viewDidLoad];
// 添加tap手势结束当前编辑(隐藏键盘⌨️)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditing)];
    [self.view addGestureRecognizer:tap];

    _textFieldObserver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidBeginEditingNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       if ([note isKindOfClass:[UITextField class]]) {
            _currentTextField = note.object;
       }
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:_textFieldObserver];
 }
#pragma mark - <结束编辑>
- (void)endEditing {
    [_currentTextField endEditing:YES];
 }
方式二: 使用UITextField的代理方法
#pragma mark - <控制器生命周期>
- (void)viewDidLoad {
    [super viewDidLoad];
// 添加tap手势结束当前编辑(隐藏键盘⌨️)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditing)];
    [self.view addGestureRecognizer:tap];
}
// 通过代理方法获取当前的 UITextField
#pragma mark - 
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    _currentTextField = textField;
    return YES;
}
#pragma mark - <结束编辑>
- (void)endEditing {
    [_currentTextField endEditing:YES];
 }

总结:

对比两种方式, 其实只是获取当前 UITextField 的方式不同而已, 能获取到 FirstResponder 的 UITextField 就能很容易控制键盘(隐藏/出现).

你可能感兴趣的:(iOS 结束当前界面编辑(隐藏键盘))