在開發過程中,為了實現點擊屏幕其它位置收起鍵盤的目的,我們使用過許多的方法。
如果是在UIViewController中收起鍵盤,除了通過調用控件的resignFirstResponder方法外,還有其它的方法。
第一種方法
重載- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法,然后在此方法中執行[self.view endEditing:YES]。
代碼示例如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];
}
如果獲取當前UIViewControll比較困難時,可以采用第二種或者第三種方法。直接執行以下兩個方法中的一個即可達到效果。
第二種方法
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
第三種方法
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
