Bar Button Item in only one of the tab bar controller navigation bar

Viewed 9141

I have a tab bar controller with 4 views controller, and have this tab bar controller in a navigation controller.

I want to display a UIBarButtonItem for just one specific view controller of the tab bar controller.

I tried to use the following

if (tabBarController.selectedViewController == customTourViewController)
    {
        [tabBarController.navigationItem setRightBarButtonItem:done];
    }

But the button doesn't show up.

If I put every view controller in a navigation controller, then the button shows up for only that view, but I end up having 2 navigation bars.

Is there any way I can implement the first solution? Thanks.

3 Answers

The accepted answer above is exactly what I needed, just wanted to convert it to Swift for those in the future.

I've added the code below to the view controller that required the bar button (I've created an add button for this example):

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

self.tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: nil)
}

In the view controllers that don't require this bar button, simply add the code below

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

self.tabBarController?.navigationItem.rightBarButtonItem = nil
}

You use viewWillAppear vice viewDidAppear because you want the bar button to appear every time the user goes to the designated view controller.

Simply put, viewDidAppear is called once at runtime, viewWillAppear will be called every time the view controller is visited.

Related