Add subview to current UINavigationBar view

What I want to do is add a custom view to my UINavigationController UINavigationBar , but only for the current visible controller.

So, I create subviews of the view that I want to add as a container, and this view to the navigation bar, getting the link with:

 let navBar = navigationController?.navigationBar as UINavigationBar! 

The result is as follows:

enter image description here

However, when I click another view controller on the UINavigationController stack, this subview is saved in the UINavigationBar for the pressed viewControllers:

enter image description here

What is the best way to add this view only in the current UINavigationBar view and not have it stored on sequential view controllers as well?

+7
ios objective-c iphone uikit swift
source share
2 answers

This happens for several reasons:

  • Adding a subview to the UINavigationBar not entirely unsupported, but can lead to odd behavior.

  • All view managers in the UINavigationController use the same UINavigationBar (therefore, the recently configured view controller did not affect your view).

If you want to do it right, here are two possible solutions:

  • Use viewWillAppear and viewWillDisappear to add / show and remove / hide your subtitle when your ideal view controller is displayed.

  • Use the UINavigationItem titleView property to assign this view, for example:

     // Example code in Obj-C, sorry! myViewController.navigationItem.titleView = [[MySearchView alloc] init]; 

    Thus, the search will be unique to this view controller.

+7
source share

I think the best way is not to use the navigation bar. You can just hide the navigation bar and create your own using UIView or UIImage (possibly UIVisualEffectView for blur in iOS 8), then add buttons to the pop view controllers (back), etc., and you will have a lot more control.

Please note that you will still be integrated into the navigation controller so that everything runs smoothly.

+3
source share

All Articles