This post is part of my collection: Swift 2 – For Beginners.
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:
class ViewController: UIViewController, UITextFieldDelegate
Then we set our view controller as the delegate of our text field:
override func viewDidLoad() { super.viewDidLoad() // this controller is the UITextFieldDelegate of our text field self.insertNameField.delegate = self }
Now we have access to a function that will be called always that the user tap “Return”. That function is “textFieldShouldReturn(textField: UITextField) -> Bool”.
To close the keyboard we resign the edition to the first responder:
// Implement delegate UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool{ textField.resignFirstResponder() return true }
This is the complete code of our view controller:
import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var insertNameField: UITextField! @IBOutlet weak var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // this controller is the UITextFieldDelegate of our text field self.insertNameField.delegate = self } @IBAction func confirmName(sender: AnyObject) { usernameLabel.text = "Hello " + insertNameField.text! } // Implement delegate UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool{ textField.resignFirstResponder() return true } // 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) } }