How to hide keyboard when return key is hit - Swift

Your problem is that you didn't delegate a textField in order to use that method. First, your class must include the UITextFieldDelegate protocol:

class yourClass: UIViewController, UITextFieldDelegate { ... }

And in the viewDidLoad() method, add this as well:

scoreText.delegate = self

And then you have to change this:

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

to this:

func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
    self.view.endEditing(true)
    return true
}

Final code:

class yourClass: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var scoreText: UITextField!

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

    func textFieldShouldReturn(_ scoreText: UITextField) -> Bool {
        self.view.endEditing()
        return true
    }
}

If this is not working, the problem is not the textFieldShouldReturn() function. Please check your outlet connections.


Try this

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