1

I have added a couple labels and an image to my navigation title bar. That all works great. But I want to cover all of it with a UIButton, but I can't get the UIButton to register any taps.

Here's what my view hierarchy looks like:

Nav Bar Views

User interaction is enabled on everything, and I have an IBAction connected to the Button like this:

@IBAction func tapProjectEdit(_ sender: UIButton) {
  print("This never fires. :(")
}

Am I not allowed to have a UIButton in the navigation bar? Is there another way to pull this off?

8
  • Have you tried to add a UITapGestureRecognizer on titleView programmatically (instead of button) ? Commented Jul 31, 2018 at 18:56
  • That's a good idea. I just tried it and it still doesn't register any taps. Commented Jul 31, 2018 at 19:05
  • If I set the view like this: self.navigationItem.titleView = buttonProjectEdit the taps work (both the IBAction and the UITapGestureRecognizer), but then it removes my labels and only the button shows up. Commented Jul 31, 2018 at 19:08
  • Can you share the code how did you create TapGesture? Commented Jul 31, 2018 at 19:11
  • Here you go: d.pr/n/3BwMAJ Commented Jul 31, 2018 at 19:13

1 Answer 1

5

I finally figured this out. I had a suspicion that the UIButton (and everything else in the View) didn't have an actual size since navigation subviews always act a little funny.

So I subclassed UIView, set that class to the View, and added this:

class FancyTitleView: UIView{
  override var intrinsicContentSize: CGSize {
    return UILayoutFittingExpandedSize
  }
}

Now it's working with a regular IBAction (no gesture recognizer required).

This post helped me discover this: custom titleView of navigationItem is not getting tapped on iOS 11

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it worked in my case too. https://stackoverflow.com/questions/46461350/custom-titleview-of-navigationitem-is-not-getting-tapped-on-ios-11/63241514#63241514

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.