I have a tab bar controller as my root view with 5 navigation controllers (one for each tab). The navigation bar in each tab will have a button that has the same functionality across all tabs. Is there an easier way to add this button (and respond to selection) than copy/pasting it into each navigation controller?
EDIT: In my custom navigation controller's child view controller, I have:
- (void)viewDidLoad
{
[super viewDidLoad];
...
CustomNavigationController *navController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeNavigationController"];
[navController addNotificationsButton:YES searchButton:NO];
}
and in the custom navigation controller I have:
-(void)addNotificationsButton:(BOOL)notifications searchButton:(BOOL)search { //Choose which bar button items to add
NSMutableArray *barItems = [[NSMutableArray alloc]init];
if (notifications) {
//Create button and add to array
UIImage *notificationsImage = [UIImage imageNamed:@"first"];
UIBarButtonItem *notificationsButton = [[UIBarButtonItem alloc]initWithImage:notificationsImage landscapeImagePhone:notificationsImage style:UIBarButtonItemStylePlain target:self action:@selector(notificationsTap:)];
[barItems addObject:notificationsButton];
}
if (search) {
//Create button and add to array
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchTap:)];
[barItems addObject:searchButton];
}
[self.navigationItem setRightBarButtonItems:barItems];
}
But I just get an empty navigation bar when the child view controller loads. Any ideas?
EDIT 2: I just had to add an argument for the view controller who's navigation bar I wanted to add buttons to. Here is the final implementation...
for CustomViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
...
CustomNavigationController *navController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeNavigationController"];
[navController addNotificationsButton:YES searchButton:NO forViewController:self];
}
For CustomNavigationController.m
-(void)addNotificationsButton:(BOOL)notifications searchButton:(BOOL)search forViewController:(UIViewController*)vc { //Choose which bar button items to add
NSMutableArray *barItems = [[NSMutableArray alloc]init];
if (notifications) {
//Create button and add to array
UIImage *notificationsImage = [UIImage imageNamed:@"first"];
UIBarButtonItem *notificationsButton = [[UIBarButtonItem alloc]initWithImage:notificationsImage landscapeImagePhone:notificationsImage style:UIBarButtonItemStylePlain target:self action:@selector(notificationsTap:)];
[barItems addObject:notificationsButton];
}
if (search) {
//Create button and add to array
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchTap:)];
[barItems addObject:searchButton];
}
vc.navigationItem.rightBarButtonItems = barItems;
}