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

因有所獲,故分享之,希望能對大家有所幫助!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容