I have an application that creates a tabbarcontroller from the AppDelegate. I wanted to have a button added to the nav bar but was unable to. Eventually I managed to get hold of some working code, but I don’t really understand it.
The steps were:
- Confirm the AppDelegate to UINavigationControllerDelegate
- Set the rootNavigationController.delegate = self
- Override navigationController:willShowViewController:animated and tabBarController:didSelectViewController
I think I follow the tabBarController:didSelectViewController code, but am lost in what is happening with navigationController:willShowViewController:animated.
- (void) tabBarController: (UITabBarController*) tabBarController didSelectViewController: (UIViewController*) viewController
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
self.tabBarController.navigationItem.title = viewController.navigationItem.title;
self.tabBarController.navigationItem.rightBarButtonItems = viewController.navigationItem.rightBarButtonItems;
self.tabBarController.navigationItem.leftBarButtonItems = viewController.navigationItem.leftBarButtonItems;
}
}
- (void) navigationController: (UINavigationController*) navigationController
willShowViewController: (UIViewController*) viewController
animated: (BOOL) animated
{
if (viewController == tabBarController)
{
UIViewController* tabViewController = tabBarController.selectedViewController;
SEL willShowSel = @selector(navigationController:willShowViewController:animated:);
if ([tabViewController respondsToSelector: willShowSel])
{
UIViewController<UINavigationControllerDelegate>* vc =
(UIViewController<UINavigationControllerDelegate>*) tabViewController;
[vc navigationController: navigationController willShowViewController: vc animated: animated];
}
}
This code is likely dealing with problems that occur using a
UITabBarControllerwithin aUINavigationController. TheUITabBarControllerdocumentation states that it needs to be the root view controller (i.e. NOT within aUINavigationController) and using it in other ways can cause problems.What the code appears to be doing is capturing the event normally passed to
viewController, checking if it is aUITabBarControllerand if it is, then it checks whether the visible view in theUITabBarControllerresponds to this method, and if it does then it passes the method (selector) call on to that view.If it is possible, I’d recommend pulling the
UITabBarControllerout from being embedded in theUINavigationController. Might take a bit of work, but will make your code compliant. (And remove need fornavigationController:willShowViewController:animated: