How to preserve a navigation toolbar across views for iOS
As this question [kind of] asks, how can I setup some toolbar items in my MainWindow.xib
and have thos开发者_Python百科e items present when I use the UINavigationController
pushViewController:animated:
.
For example, my application has:
MainWindow.xib
, which contains aUINavigationController
with navigation bar and a toolbar.AViewController.xib
, which just contains aUITableView
.
At some point, our user presses a toolbar button and the associated action performs:
- (void)someAction {
[self.navigationController pushViewController:[[AViewController alloc]
initWithNibName:nil bundle:nil]
animated:YES];
}
When the new view gets pushed, it contains a blank toolbar, instead of the toolbar with the same items as before. What's the preferred method for keeping them the same? I feel like I'm just missing something simple! Thanks in advance!
I would have one of my classes adopt the UINavigationControllerDelegate
protocol and implement the navigationController:willShowViewController:animated:
method like this,
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
[viewController setToolbarItems:toolbarItems animated:NO];
}
where I create and store toolbarItems
in the delegate class. One of the likely candidates for being the delegate is the application delegate class as it is most probable place where you will instantiate the navigation controller.
I've ended up switching to Deepak's answer, but I also thought I would provide this in case it helps someone (or if people want to provide feedback).
In my showAction
method defined above, I refactored it to this:
- (void)someAction {
AViewController *av = [[AViewController alloc]
initWithNibName:nil bundle:nil];
[av setToolbarItems:[[self.navigationController toolbar] items]];
[self.navigationController pushViewController:av animated:YES];
}
精彩评论