美文网首页iOS开发iOS
iOS收起键盘的三种方法

iOS收起键盘的三种方法

作者: GodLiekZ | 来源:发表于2018-04-26 11:27 被阅读0次

在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];
}

相关文章

网友评论

    本文标题:iOS收起键盘的三种方法

    本文链接:https://www.haomeiwen.com/subject/qmeplftx.html