How to dismiss number pad keyboard by tapping anywhere

后端 未结 15 2158
梦如初夏
梦如初夏 2020-12-04 17:53

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 te

相关标签:
15条回答
  • 2020-12-04 18:15

    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) 
      }
      
    0 讨论(0)
  • 2020-12-04 18:18

    For Swift, the easiest for dismissing keypad for all text fields by tapping anywhere outside the text field is:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
    {
        self.view.endEditing(true)
    }
    
    0 讨论(0)
  • 2020-12-04 18:19

    You can implement @mbm's answer really nicely by putting a didSet on the outlet and attaching your inputAccessoryView there:

    Swift code:

      @IBOutlet var input: UITextField! { didSet {
        let toolbar = UIToolbar(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 44)))
        toolbar.items = [
          UIBarButtonItem(barButtonSystemItem: .done, target: self.input,
            action: #selector(resignFirstResponder))
        ]
        input.inputAccessoryView = toolbar
      }}
    

    In xcode 8 / iOS 10 It ends up looking something like this:

    0 讨论(0)
提交回复
热议问题