Reputation: 6691
I am creating a NavigationController in application delegate and adding a custom button to it programatically with the following code.
self.navCntrl = [[UINavigationController alloc]initWithRootViewController:self.viewController];
// -- Adding INFO button to Navigation bar --
UIBarButtonItem *infoButton = [[UIBarButtonItem alloc]
initWithTitle:@"i"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(showInfo)];
self.navCntrl.topViewController.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:infoButton, nil];
self.window.rootViewController = self.navCntrl;
But problem is that when I push a second page to navigationController the cancel button is not shown on the navigation bar. If I go back to first page, the cancel button is there. So, apparently the button is added only for the first view.
One rescue to this is to add the above custom button repeatedly in every view controller(copy and pasting code). I believe there must be some other way as same navigation controller is being used. What is it if there is any ?
Thanks in advance
Upvotes: 0
Views: 375
Reputation: 53561
The buttons that are shown in the navigation controller's navigation bar don't belong to the navigation controller, they're properties of each individual view controller's navigation item. Usually, these buttons perform actions that apply to the view controller that is currently being shown, and not to the whole navigation controller.
If you really need all view controllers in the navigation hierarchy to have the same button(s), without copying and pasting the code everywhere, you could set yourself as the navigation controller's delegate
and implement navigationController:willShowViewController:animated:
like this:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
//Assuming you have initialized self.infoButtonItem elsewhere...:
viewController.navigationItem.rightBarButtonItem = self.infoButtonItem;
}
Upvotes: 1