Could someone please help me recognise a tap when a user taps on the Title in the Navigation Bar?

I would like to recognise this tap and then animate the tableHeaderView appearing. Possibly sliding the TableView down.

The idea being that the user can then select a quick option (from the tableViewHeader) to re-populate the TableView.

However I cannot recognise any taps. I'm using Swift.


Solution 1:

UINavigationBar does not expose its internal view hierarchy. There is no supported way to get a reference to the UILabel that displays the title.

You could root around in its view hierarchy “manually” (by searching through its subviews), but that might stop working in a future iOS release because the view hierarchy is private.

One workaround is to create a UILabel and set it as your view controller's navigationItem.titleView. It's up to you to match the style of the default label, which may change in different versions of iOS.

That said, it's pretty easy to set up:

override func didMove(toParentViewController parent: UIViewController?) {
    super.didMove(toParentViewController: parent)

    if parent != nil && self.navigationItem.titleView == nil {
        initNavigationItemTitleView()
    }
}

private func initNavigationItemTitleView() {
    let titleView = UILabel()
    titleView.text = "Hello World"
    titleView.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    let width = titleView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).width
    titleView.frame = CGRect(origin:CGPoint.zero, size:CGSize(width: width, height: 500))
    self.navigationItem.titleView = titleView

    let recognizer = UITapGestureRecognizer(target: self, action: #selector(YourViewController.titleWasTapped))
    titleView.userInteractionEnabled = true
    titleView.addGestureRecognizer(recognizer)
}

@objc private func titleWasTapped() {
    NSLog("Hello, titleWasTapped!")
}

I'm setting the size of the label to its natural width (using sizeThatFits:), but I'm setting its height to 500. The navigation bar will keep the width but shrink the height to the bar's own height. This maximizes the area available for tapping (since the natural height of the label might be only ~22 points but the bar is 44 points high).

Solution 2:

From the answers, we can tell there are two approaches to do this.

  1. Add a UITapGestureRecognizer to the titleView. This does not seem elegant and requires you to manually set the navigation bar title font so I would not recommend it.
  2. Add a UITapGestureRecognizer to the navigationBar. This seems pretty elegant but the problem with the posted answers that take this approach is that they all result in preventing controls within the navigation bar from working. Here is my implementation of this method that allows your controls to continue working.

// Declare gesture recognizer
var tapGestureRecognizer: UITapGestureRecognizer!

override func viewDidLoad() {

    // Instantiate gesture recognizer
    tapGestureRecognizer = UITapGestureRecognizer(target:self, action: #selector(self.navigationBarTapped(_:)))
}

override func viewWillAppear(_ animated: Bool) {

    // Add gesture recognizer to the navigation bar when the view is about to appear
    self.navigationController?.navigationBar.addGestureRecognizer(tapGestureRecognizer)

    // This allows controlls in the navigation bar to continue receiving touches
    tapGestureRecognizer.cancelsTouchesInView = false
}

override func viewWillDisappear(_ animated: Bool) {

    // Remove gesture recognizer from navigation bar when view is about to disappear
    self.navigationController?.navigationBar.removeGestureRecognizer(tapGestureRecognizer)
}

// Action called when navigation bar is tapped anywhere
@objc func navigationBarTapped(_ sender: UITapGestureRecognizer){

    // Make sure that a button is not tapped.
    let location = sender.location(in: self.navigationController?.navigationBar)
    let hitView = self.navigationController?.navigationBar.hitTest(location, with: nil)

    guard !(hitView is UIControl) else { return }

    // Here, we know that the user wanted to tap the navigation bar and not a control inside it 
    print("Navigation bar tapped")

}