Easy way to dismiss keyboard?

I have quite a few controls scattered throughout many table cells in my table, and I was wondering if there's an easier way to dismiss the keyboard without having to loop through all my controls and resigning them all as the first responder. I guess the question is.. How would I get the current first responder to the keyboard?


尝试:
[self.view endEditing:YES];


You can force the currently-editing view to resign its first responder status with [view endEditing:YES] . This hides the keyboard.

Unlike -[UIResponder resignFirstResponder] , -[UIView endEditing:] will search through subviews to find the current first responder. So you can send it to your top-level view (eg self.view in a UIViewController ) and it will do the right thing.

(This answer previously included a couple of other solutions, which also worked but were more complicated than is necessary. I've removed them to avoid confusion.)


You can send a nil targeted action to the application, it'll resign first responder at any time without having to worry about which view currently has first responder status.

Objective-C:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

Swift 3.0:

UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)

Nil targeted actions are common on Mac OS X for menu commands, and here's a use for them on iOS.

链接地址: http://www.djcxy.com/p/7694.html

上一篇: 动态更改UISearchBar的键盘类型

下一篇: 简单的方法来解除键盘?