iOS: Dismiss Keyboard Programmatically

 ·  · 

Tips about how to dismiss iOS keyboard programmatically.

Generally, there are two ways to dismiss iOS keyboard programmatically.

The first method is to send resignFirstResponder message to text-based view that is currently the first responder.

[yourTextField resignFirstResponder];

or code in Swift:

yourTextField.resignFirstResponder()

Alternatively, if you are not sure which text-based view exactly is the first responder, you can simply call endEditing method of the super UIView. For example, send endEditing message to the view of UIViewController.

[self.view endEditing:YES];

Code in Swift:

self.view.endEditing(true)

The latter way is more effective and convenient.