I have a UINavigationController that displays a UITabBarController. I am trying to add custom icons for the tab bars. I have placed the following code in AppDelegate.m didFinishLaunchingWithOptions
:
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
tabBarItem1.selectedImage = [[UIImage imageNamed:@"iconSelected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.image = [[UIImage imageNamed:@"icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.title = nil;
With this code I receive the following NSException:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UINavigationController tabBar]: unrecognized selector sent to instance 0x7faed26343e0'
My assumption is that somehow in *tabBar
I need to access the tabBar through the UINavigationController. (I.E. - UITabBar *tabBar = UINavigationController.tabBarController.tabBar;
) However, this does not work either.
What is the proper way to achieve what I am looking to do?
If your tabBarController
is within a navigation controller, you need to get a reference to it from that navigation controller. It can be found as the first object in the navigation controllers' viewControllers
property (or, if no other controllers have been pushed onto the navigation controller, the topViewController
property). Replace:
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
with:
UINavigationController *navCtrl = (UINavigationController *)self.window.rootViewController;
UITabBarController *tabBarController = (UITabBarController *)navCtrl.viewControllers[0];