Bar Button Item in only one of the tab bar controller navigation bar
Alternatively you can implement viewWillDisappear in the same view where you need the button.
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
self.tabBarController.navigationItem.rightBarButtonItem = nil;
}
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.
In my individual view controllers for the individual tabs, I have the following in the one that needs the button:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonSystemItemDone target:nil action:nil];
self.tabBarController.navigationItem.rightBarButtonItem = rightButton;
}
And in the view controllers that don't need the button, I have:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.tabBarController.navigationItem.rightBarButtonItem = nil;
}
So, if it's not working for you, I'm not sure if it's your reference to tabBarController
without the self
designation (if I omit the self
I get a compiler error). And where is this code because if it's in your tabBarController subclass, then you want self.navigationItem.rightBarButtonItem
, right? Do you have your own ivar defined for that variable name? Or are you sure that done
is defined properly (i.e. not nil
)? Or are you sure this code is being called at all (perhaps set a breakpoint or insert a NSLog
and make sure this code is being reached)?