2

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.

enter image description here

I need to make the resigning work in the area enclosed in yellow, including the button shown by the arrow.

toing_toing
  • 2,334
  • 1
  • 37
  • 79

4 Answers4

3

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)

}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

Call this line inside of your button action BEFORE you are calling your MENU on button:

YourSearchOutlet.resignFirstResponder()
Pang
  • 9,564
  • 146
  • 81
  • 122
Avinash Mishra
  • 797
  • 9
  • 19
1

Try to add tap gesture on navigation bar :

  override func viewDidLoad() {
        super.viewDidLoad()

        let navSingleTap = UITapGestureRecognizer.init(target: self, action: #selector(self.tap(_:)))
        navSingleTap.numberOfTapsRequired = 1
        self.navigationController?.navigationBar.subviews[1].isUserInteractionEnabled = true
        self.navigationController?.navigationBar.subviews[1].addGestureRecognizer(navSingleTap)
        }

    func tap() {
      //  do your work 
    }
KKRocks
  • 8,222
  • 1
  • 18
  • 84
  • I tried after changing `tap()` to `tap(_ recognizer: UIGestureRecognizer)` as per the accepted answer and it worked. – toing_toing Apr 27 '17 at 09:59
1

Subclass UINavigationBar and set it as the custom class of the Navigation Bar in the Storyboard.

//  NavigationBar.swift

import UIKit

class NavigationBar: UINavigationBar {

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.window?.endEditing(true)
    }

}
Daniel
  • 13
  • 5