Search code examples
iosstoryboardtouchesbegan

Could I set vc's view becomeFirstResponder by touchesBegan func in storyboard?


In code, I can use this below method to let vc's view becomeFirstResponder, and play down the show-up keyboard.

enter image description here

the code is below:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.view.endEditing(true)
}

Could I set this function in my storyboard? or there is some way easier for self.view.endEditing(true) when click self.view?

Because if not do this, I will copy the function upper to almost every vc.


Solution

  • Just put this somewhere in the code and it would resolve your issue with code duplicating

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

    I'm not sure tho if it's a good way of doing this, maybe you'd like to rethink the architectural issues of resigning the textfield's responder, regards of what you really need.