The easy way to dismiss the keyboard in iOS

If you want to dismiss the iOS keyboard programmatically in your app without worrying about which view is the first responder, try the following:

Approach #1: Using the Responder Chain

In Swift:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

In Objective-C:

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

This will resign the first responder (and dismiss the keyboard) every time, without you needing to send resignFirstResponder to the proper view. No matter what, this will dismiss the keyboard. It’s by far the best way to do it: no worrying about who the first responder is.

Approach #2: Using UIView’s endEditing

A reader pointed out that you can also use -[UIView endEditing:] to dismiss the keyboard (assuming your text field is a subview of the view you call this on). Most of the time, you should be able to do the following:

In Swift:

self.view.endEditing(true)

In Objective-C:

[self.view endEditing:YES];

One benefit to this approach is that you can use the return value of endEditing to find out whether the keyboard was dismissed or not.

The key here is that you need to have a reference to the view, so you can only use this approach from a view controller. In practice, you’ll probably be dismissing the keyboard from a view controller most of the time anyway, but the nil-targeted action approach (using UIApplication) works from anywhere.

Further Reading

I first learned the nil-targeted action approach from Sean Heber. Thanks, Sean!

The Amazing Responder Chain explains the responder chain and why the first approach works.

How to Dismiss UITextField’s Keyboard in your Swift App shows how to set up a text field and dismiss it with the second (UIView) approach above.