Search code examples
swiftkeyboard

Why is the textFieldShouldReturn function not being called?


The textFieldShouldReturn function is not being called at all: there are no errors but the keyboard does not respond at all.

My case is different from How to hide keyboard in swift on pressing return key? as in my case nothing is happening at all and other cases are in Objective-C.

Here is my code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        resignFirstResponder()
        return true
    }
}

textField is an outlet to a text field on my storyboard. I also tried self.endEditing instead of resignFirstResponder.


Solution

  • The rest of this answer is still very useful, and I'll leave it there as it can potentially help other askers... but here, I missed the obvious problem with this specific example...

    We're not calling resignFirstResponder on the text field. We're calling it on the view controller. We need to call it on the text field, so modify your code to look like this:

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    

    A UITextField will only call the textFieldShouldReturn property on the object which is its delegate.

    We can fix this programmatically by adding a viewDidLoad method to set that:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textField.delegate = self
    }
    

    But we can also set this up via the storyboard at build time.

    Right click on the textfield to check and see whether or not the delegate has been set:

    enter image description here

    If that circle next to delegate is unfilled, we haven't set the delegate for our UITextField yet.

    To set the delegate, hover over this circle. It will change to a plus sign. Now click and drag to the view controller that you want to delegate the text field (the view controller the text field is part of).

    enter image description here

    When you've appropriately hooked the view controller up as a delegate, this menu should look like this:

    enter image description here