Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add subview to current view's UINavigationBar only

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:

enter image description here

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

enter image description here

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?

like image 996
Thanos Avatar asked Feb 16 '15 20:02

Thanos


1 Answers

This is happening for a few reasons:

  1. Adding a subview to a UINavigationBar isn't exactly unsupported, but could possibly result in odd behavior.

  2. 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:

  1. Use viewWillAppear and viewWillDisappear to add/show and remove/hide your subview when your ideal view controller is visible.

  2. 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.

like image 140
mattsven Avatar answered Oct 28 '22 13:10

mattsven