I am developing an swift 3 app that has a navigation bar in every page. The navigation bar also has a button in the left. I need to resign the keyboard on touch of any object in the screen. I tried with the usual
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
but it works for all other parts of the view except the navigation bar. I tried adding the following code:
self.navigationController?.navigationBar.endEditing(true)
to the touchesBegan
function but it did not work, presumable because I do not have a navigation controller, I just added the searchbar in the storyboard.
How can I get the keyboard to resign on tap of the navigation bar, including the button in the navigation bar?
This is important to my app, because, as you can see below, it is the largest space available for the user to tap without changing the view.
I need to make the resigning work in the area enclosed in yellow, including the button shown by the arrow.
for e.g
override func viewDidLoad() {
super.viewDidLoad()
let hideKeyboard = UITapGestureRecognizer(target: self, action: #selector(self.navigationBarTap))
hideKeyboard.numberOfTapsRequired = 1
navigationController?.navigationBar.addGestureRecognizer(hideKeyboard)
}
and handle the action as
func navigationBarTap(_ recognizer: UIGestureRecognizer) {
view.endEditing(true)
// OR USE yourSearchBarName.endEditing(true)
}