I have an app with a navcontroller created in the appdel. Each vc pushed in has a block of code in the viewdidload that sets up the toolbar. The toolbar is always the same. Is there a way for me to just create this code once – and not put it in every vc?
[self.navigationItem setHidesBackButton:YES];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleBordered target:self action:@selector(backClicked)];
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *storyBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Sto" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
storyBtnItem.tag = 1;
UIBarButtonItem *renderBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Ren" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
renderBtnItem.tag = 2;
UIBarButtonItem *amenBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Ame" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
amenBtnItem.tag = 3;
UIBarButtonItem *availBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Availability" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
availBtnItem.tag = 4;
UIBarButtonItem *eopBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Eq" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
eopBtnItem.tag = 5;
UIBarButtonItem *stkBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"St" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
stkBtnItem.tag = 6;
UIBarButtonItem *movBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Fi" style:UIBarButtonItemStyleBordered target:self action:@selector(toolbarControl:)];
movBtnItem.tag = 7;
NSArray *items = [NSArray arrayWithObjects:flexibleSpaceLeft, stoBtnItem, reBtnItem, ameBtnItem, avaBtnItem, eBtnItem, stBtnItem, mvBtnItem, nil];
[self setToolbarItems:items];
[self.navigationController.toolbar setTintColor:[UIColor colorWithRed:79.0/255.0 green:145.0/255.0 blue:205.0/255.0 alpha:1.0]];
Just do
vc.toolbarItems = self.toolbarItems(wherevcis the view controller to be pushed) in the method where you are pushing the next view controller.eg:
Also, you don’t need to do this in the
-viewDidLoadmethod, setting the navigation items and toolbar items does not require the view to be loaded and can thus be done in yourinitorawakeFromNibmethod. If you do it in-viewDidLoadyou are potentially setting the items multiple times.