Denis Balko
Denis Balko

Reputation: 1596

Custom title view as large title in iOS 11 new navigation bar

I am using a button as a title view for my UITableViewController which opens a dropdown list of categories. Selecting a category filters content of the table view by the selected category.

The button shows the name of the selected category plus a small arrow, similar to how iBooks used to look (or maybe still looks? I haven't used it in a while). I would therefore like it to have the same behaviour as a standard title and have it be large at first and collapse when the table view is scrolled.

Is there a way to do this?

Thanks

Upvotes: 10

Views: 9772

Answers (4)

iAmcR
iAmcR

Reputation: 889

It seems because of the new large titles, IOS11 requires the constraints on the custom view in the navigationItem.titleView to be set.

Do this for example:

customView.widthAnchor.constraint(equalToConstant: 200).isActive = true
customView.heightAnchor.constraint(equalToConstant: 44).isActive = true

self.navigationItem.titleView = customView

Note this must be done for both width and height.

It should work. No need to add a button, at least in my case...

This was suggested by Apple to ensure that you don't have zero-size custom views. See slide 33 in https://developer.apple.com/videos/play/wwdc2017/204/

Upvotes: 8

Juraj Antas
Juraj Antas

Reputation: 2712

Well, I had same problem. I have UIButtons in UINavigationItem.titleView and those were not reacting to touches at all. Problem is that the view where those buttons are where of size (0,0) because of auto layout. So to fix this problem you need to add additional view into your custom view, lets call it "contentView" and put all your controls inside that contentView. Also, contentView must have defined size with constraints. Quick test is to add width and height constraint to contentView. And all works again.

Hope that this helps someone.

Upvotes: 1

Juan Sagasti
Juan Sagasti

Reputation: 344

Seems like a bug in iOS 11: https://forums.developer.apple.com/thread/82466

I provisionally implemented this workaround:

    private lazy var navBarActionButtonIOS11: UIButton = {
        button.addTarget(self.navTitleView, action: #selector(self.navTitleView.didTapView), for: .touchUpInside)
        return button
    }()

[...]

        navigationItem.titleView = navTitleView
        if #available(iOS 11.0, *), let navBar = navigationController?.navigationBar {
            navBarActionButtonIOS11.removeFromSuperview()
            navBar.addSubview(navBarActionButtonIOS11)
            navBarActionButtonIOS11.center.x = navBar.center.x
        }

Another solution could be to just assign a UIButton to navigationItem.titleView directly.

I hope Apple fixes this soon!

Upvotes: 2

Aleksey Mazurenko
Aleksey Mazurenko

Reputation: 643

Looks like touches are broken for navigationItem.titleView. Gestures, tap events and buttons - nothing works

Upvotes: 4

Related Questions