Search code examples
iosobjective-ciphoneuitabbaritem

iOS Tab Bar custom items images, tab bar draws gray images on the left


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


Solution

  • 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...