Easy way to dismiss keyboard?
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.
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 (e.g. 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.)
Try:
[self.view endEditing:YES];