iOS收起键盘的三种方法

在UIViewController中收起键盘,除了调用相应控件的resignFirstResponder。例:

  • 利用textField的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    if (![self.textField isExclusiveTouch]) {
        [self.textField resignFirstResponder];
    }
    return YES;
}

还有另外的三种方法:

  • 重载UIViewcontroller中的touchesBegin方法,然后在里面执行[self.view endEditing:YES]; ,这样单击UIViewController的任意地方就可以收起键盘。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}
  • 直接执行[[UIApplication sharedApplication] sendAction: @selector(resignFirstResponder to:nil from:nil forEvent:nil];,用于在获得当前UIViewController比较困难的时候用。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

     [[UIApplication sharedApplication]sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}
  • 直接执行 [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

因有所获,故分享之,希望能对大家有所帮助!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容