What I want to do is add a custom view to my UINavigationController's UINavigationBar but only for the current visible view controller.
So I build the subviews of the view I want to add in a container view and this view to the navigation bar by getting a reference with:
let navBar = navigationController?.navigationBar as UINavigationBar!
The result looks like this:

However, when I push another view controller in the UINavigationController stack, this subview persists in the UINavigationBar of the pushed viewControllers as well:

What's the best way to add this subview only in my current view's UINavigationBar and don't have it persisted on consecutive view controllers as well?
This is happening for a few reasons:
Adding a subview to a UINavigationBar isn't exactly unsupported, but could possibly result in odd behavior.
All view controllers in a UINavigationController share the same UINavigationBar (which is why a newly pushed view controller didn't have any affect on your subview).
If you want to do this properly, here's two possible solutions:
Use viewWillAppear and viewWillDisappear to add/show and remove/hide your subview when your ideal view controller is visible.
Use UINavigationItem's titleView property to assign this view, e.g.:
// Example code in Obj-C, sorry!
myViewController.navigationItem.titleView = [[MySearchView alloc] init];
This way the search view will be unique to that view controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With