0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

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];
pbasdf
  • 21,386
  • 4
  • 43
  • 75
  • This code produces [LaunchScreenViewController tabBar]: unrecognized selector sent to instance. LaunchScreenViewController is the VC immediately after my UINavigationController. Why would it be calling this LaunchScreenVC as it is not my very first VC? @pbasdf – Tyler Riedal Oct 26 '14 at 21:17
  • Sorry, I assumed your sequence was NavController -> TabBarController . What is the actual sequence? – pbasdf Oct 26 '14 at 21:28
  • The sequence is: UINavigationController > LaunchScreenVC > SignUpVC & LogInVC > UITabBarController > UserProfileVC & Contacts VC I tried to upload a picture of my storyboard but I currently do not have enough reputation points. I hope that you are able to visualize it. @pbasdf – Tyler Riedal Oct 26 '14 at 21:42
  • Wow, so that tabBarVC is a long way down the tree. Do you really want to set its tabBar from `didFinishLaunchingWithOptions`? Can't you set it all in the storyboard? – pbasdf Oct 26 '14 at 21:51
  • I didn't realize that it could be set from storyboard. Thanks for the help! @pbasdf – Tyler Riedal Oct 26 '14 at 22:22