0

I try to change colors of the tab bar items images, for this I am using next code:

// Generate a tinted unselected image based on image passed via the storyboard.
for (UIViewController *vc in tabBarController.viewControllers) {
    UITabBarItem *item = vc.tabBarItem;
    UIImage *image = item.image;
    UIImage *imageSel = [image imageWithColor:selectedColor];
    UIImage *imageUnsel = [image imageWithColor:unselectedColor];

    // Next is not working to set unselected image! 
    // But setFinishedSelectedImage does.
    //item.selectedImage = imageSel;
    item.image = imageSel;
    //[item setFinishedSelectedImage:imageSel withFinishedUnselectedImage:imageUnsel];
}

UITabBarItem *item = tabBarController.moreNavigationController.tabBarItem;
UIImage *image = [UIImage imageNamed:@"menu-more"];
UIImage *imageSel = [image imageWithColor:selectedColor];
UIImage *imageUnsel = [image imageWithColor:unselectedColor];
item.image = imageSel;
// [item setFinishedSelectedImage:imageSel withFinishedUnselectedImage:imageUnsel];

imageWithColor: is UIImage extension to generate image with color using alpha values of the original image.

First time the code executes, everything is fine.

After I change the color (calling the above code), all tab bar items are shown on the left of the tab bar with text. Happens in both emulator and device (iPhone + iPad). Is this a bug?

enter image description here

Borzh
  • 5,069
  • 2
  • 48
  • 64

2 Answers2

0

You can set image to tabbaritem by using storyboard itself. For changing color to selected tabbaritem no need to write any for loop. You can use below line.

        [[UITabBar appearance] setTintColor:[UIColor greenColor]];
Rajesh
  • 124
  • 9
  • This will only change the selected item's color, but unselected items will appear gray. Already tried that. – Borzh Oct 05 '17 at 14:58
  • May i know y you are using selected and unselected colors for tabbaritem image. – Rajesh Oct 06 '17 at 10:41
  • Yes, both, actually unselected color is same as selected but with only 0.5 of alpha. – Borzh Oct 06 '17 at 19:00
0

Well I figured the fix. Instead of setting image of UITabBarItem you need to create the UITabBarItem from scratch and set the image there, like this:

for (UIViewController *vc in tabBarController.viewControllers) {
    UITabBarItem *newItem = [[UITabBarItem alloc] initWithTitle:someTitle image:someImageUnsel selectedImage:someImageSel];
    vc.tabBarItem = newItem;
}

UITabBarItem *newItem = [[UITabBarItem alloc] initWithTitle:someTitle image:someImageUnsel selectedImage:someImageSel];
tabBarController.moreNavigationController.tabBarItem = newItem;

There is an issue with this solution though: MoreNavigationController will pop back after setting it's tabBarItem. Common Apple, wtf?!

If anyone can contribute a better solution, please do...

Borzh
  • 5,069
  • 2
  • 48
  • 64