0

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?

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
  • Try this : **https://github.com/hackiftekhar/IQKeyboardManager** and put this line `IQKeyboardManager.shared.shouldResignOnTouchOutside = true` in your `didFinishLaunchingWithOptions` so when you touch outside it will dismiss keyboard. – Kuldeep Nov 20 '18 at 11:25

1 Answers1

0
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)
    }
}
Daniyal Raza
  • 352
  • 3
  • 13