I have UIViewController
with UITextfield
and several other elements (several subviews and buttons). I want to close the keyboard when tapped somewhere outside of the UITextfield
.
I know there is an answer Close iOS Keyboard by touching anywhere using Swift , but this way doesn't work if user taps on viewController's subviews or buttons. I can add the similar UITapGestureRecognizer
for each subViews and buttons, but is there a smarter way to resolve this?
extension UIViewController{
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
Also if you have elements in a UIScrollView, add this method too:
extension UIScrollView {
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.next?.touchesBegan(touches, with: event)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.