Search code examples
cocoaios5uiviewcontrolleruinavigationcontrolleruinavigationbar

Keep leftBarButtonItems on new UIViewcontroller when pushed


I have a UIViewController embedded in a UINavigationController. The rootViewController now contains already some buttons as leftBarButtonItems.

Now when I push a new UIViewController on top of the UINavigationController I want the new UIViewController to keep the existing leftBarButtonItems extended with the Back-Button.

Right now the situations is as follows: When I push the new UIViewController then the existing leftBarButtonItems disappear and only the Back-Button is visible.


Solution

  • Each UIViewController has it's own "navigationItem" property, which acts as the navigation bar representation for that viewcontroller. When you add buttons to the navigationItem of a particular UIViewController they are limited in scope to the viewcontroller to which they were added, and they don't persist into other viewcontrollers.

    Basically, you'll have to add the buttons to the navigationItem of each viewcontroller as it loads. You can make this simpler by writing adding a method to do this work to a class other than your UIViewControllers. What happens when you touch each button might be viewcontroller specific though, so you'll have to think through how touch actions will be fed back to the relevant viewcontroller. Perhaps introduce some kind of NavigationBarDelegate protocol or something?