Search code examples
objective-cuicoloruitabbaritem

Get the color of uitabbaritem with unselected state?


I changed the color of uitabbaritem (text + image) with unselected state. I would like to know if there is a way to get this color ? I know we can get the selected color with [UITabBar appearance].selectedImageTintColor but for the unselected color I don't know if it's possible.

Thanks in advance,

JC


Solution

  • To find out the actual colors for UITabBarItem even without calling any appearance API before use the following code. It queries the view hierarchy and uses the first and the 2nd button for figuring out the actual UIColor. For IOS9 it gives "UIDeviceRGBColorSpace 0 0.478431 1 1" (#007aff in hex) for the selectedColor and "UIDeviceWhiteColorSpace 0.572549 1" (#929292 in hex) for the inactiveColor. This might change of course in future versions. To get a concrete color for an item with tintColors, appeareance etc set use findTabBarLabel() for the actual UITabBar.

    static UILabel* findTabBarLabel(UITabBar* tb,NSString* text)
    {
      for (UIView* btn in tb.subviews) {
        if (![btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {continue;}
        for (UIView* sv in btn.subviews) {
          if (![sv isKindOfClass:NSClassFromString(@"UITabBarButtonLabel")]) {continue;}
          UILabel* l=(UILabel*)sv;
          if ([text isEqualToString:l.text]) {
            return l;
          }
        }
      }
      return nil;
    }
    
    static void retrieveTabBarSystemColors()
    {
      UITabBarController* tc=[[UITabBarController alloc] init];
      UITabBarItem* it1=[[UITabBarItem alloc] initWithTitle:@"foo" image:nil tag:1];
      UIViewController* vc1=[[UIViewController alloc] init];
      vc1.tabBarItem=it1;
      UITabBarItem* it2=[[UITabBarItem alloc] initWithTitle:@"bar" image:nil tag:2];
      UIViewController* vc2=[[UIViewController alloc] init];
      vc2.tabBarItem=it2;
      tc.viewControllers=@[vc1,vc2];
      UITabBar* tb=tc.tabBar;
      UILabel* label1=findTabBarLabel(tb,@"foo");
      NSLog(@"Tab bar item active:%@",label1.textColor.description);
      UILabel* label2=findTabBarLabel(tb,@"bar");
      NSLog(@"Tab bar item inactive color:%@",label2.textColor.description);
    }