iOS收起鍵盤的三種方法

在UIViewController中收起鍵盤,除了調(diào)用相應(yīng)控件的resignFirstResponder。例:

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

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

還有另外的三種方法:

  • 重載UIViewcontroller中的touchesBegin方法,然后在里面執(zhí)行[self.view endEditing:YES]; ,這樣單擊UIViewController的任意地方就可以收起鍵盤。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}
  • 直接執(zhí)行[[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];
}
  • 直接執(zhí)行 [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容