なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOS UITextField How to dismiss the keyboard when user tap a retrun key.

Introduction

This article show you that how to dismiss the keyboard when user tap a return key on UITextField of iOS.

In fact, this way shows on the iOS SDK document. I've never knew it.

Solution

  1. Adapt the UITextFieldDelegate on your ViewController

  2. Assign the self in the textField's delegate

  3. Implement the textFieldShouldReturn: method

  4. On textFieldShouldReturn: method, call the resignFirstResponder()

  5. And return the value true or false

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var textField : UITextField!
    override func viewDidLoad() {
        self.textField.delegate = self 
    }

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

Detail

textFieldShouldReturn:

This textFieldShouldReturn: method is called when user tap the return button on the keyboard.

If you want to do its default behavior for the return button, you need to return true otherwise false.

In this case, to dismiss the keyboard, it wouldn't be a problem that which value is returned.

resignFirstResponder

First Responder means like a focus.

So, when this method call, the focus will resign from the UITextField's instance.

The keyboard will dismiss when the focus would out.

ReferenceURL