Website Links

Friday 11 December 2015

Swift - Hide keyboard when clicking outside UITextField or return is tapped

Sometimes it can obscure the view when a user enters something in a UITextField and the keyboard stays open even after they have clicked outside the keyboard, or tapped return. The following code will help you close the keyboard when appropriate. However, first you need to set up your text field and make the appropriate view controller be its delegate, and implement UITextFieldDelegate:



The corresponding code is as follows:

  class GameViewController: UIViewController, UITextFieldDelegate {

    ...

    override func touchesBegan(touches: Set, 
      withEvent event: UIEvent?) {
      self.view.endEditing(true)
    }

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

    ...

  }

Additionally, if you have any buttons with IBActions attached to them you may need to have the line self.view.endEditing(true) in these also.

No comments:

Post a Comment