How to dismiss number pad keyboard by tapping anywhere

Viewed 59240

I'd like to know the simplest code to dismiss the number pad keyboard when tapping anywhere outside the number pad. It's a simple application to input a number inside a text field and then a user can dismiss the keyboard after the user finishes typing the numbers on the text field. Thanks! :)

16 Answers

For swift 3/4 I like this case:

  1. View Controller is subclass for UITextFieldDelegate
  2. In the viewDidLoad function, you have to set yourPhonePadField.delegate = self
  3. And override this function:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       self.view.endEditing(true) 
    }
    

Swift 5

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
           self.view.endEditing(true)
           return true
 }
Related