Swift 2 examples – #2 Close keyboard after edit

iOS applications show automatically the keyboard when you click on a text field. The keyboard hides the bottom of your application and is not closed automatically.
In this example we will see how to close the keyboard when the user tap “Return” or touch out of the text field.

Close keyboard when the user touch out of the text field

This is pretty easy, just add this code to your view controller:

// close keyboard when the user touch somewhere
// that is not the keyboard of the text field
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}

Close keyboard when the user tap Return

To do this our view controller has to implement the interface UITextFieldDelegate: