Hide / Close keyboard after typing in uitextfield

This tutorial has been updated for X code 7.3 & swift 2.2

In this tutorial I am going to show you three methods to close keyboard.

Method 1: closing keyboard when button is pressed

1. First lets set up the x code project as usual. Create new single view application X code project. Set the values as follows and save it on your desktop.

new x code project

 

2. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

size iPhone 4 inch

 

3. Add textfield and a button to the main storyboard.

textfield & button

 

4. Select button and set its text to Submit.

button text to submit

 

5. Open assistant editor and add textfield to the swift file

textfield as outlet

 

6. Then connect button to the swift file

button as action

 

7. Add following line to button. Tip: If you add the following line in any other function & trigger the function then keyboard will close.

    @IBAction func buttonPressed(sender: UIButton) {
        // 7
        textBox.resignFirstResponder()
    }

8. Now run the project in iPhone 5s. Start typing text in the textfield. Then press submit button. The keyboard should disappear

Screen Shot 2015-03-01 at 12.31.05 pm

Method 2: closing keyboard when pressed on return button

9. To the previous project add UITextFieldDelegate to view controller class

// 9
class ViewController: UIViewController, UITextFieldDelegate {

10. Open main storyboard & right click on the text field or control + click on text field. Connect delegate to the view controller.

AFMbPYs3y9

11. Then add following code at the bottom of view controller class. Tip: Any code added in this function will trigger when you press return button.

    // 11
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        self.view.endEditing(true)
        
        return true
    
    }

12. Now run the project in iPhone 5s. Type something in textfield & press return button.

Screen Shot 2015-03-01 at 12.31.05 pm

Method 3: Closing keyboard when touched on empty space outside textfield

13. To previous project add the following code at end of view controller class. Tip: Any code added to following function will trigger when you press on empty space outside text field.

    // 13
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        textBox.resignFirstResponder()
    
    }

14. Now run project in iPhone 5s. Type something in text field & touch on empty space outside text field.

Screen Shot 2015-03-01 at 12.31.05 pm
Download Closing Keyboard X Code file

Total 7 Votes
3

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?