Domanda

Okay, I know there are already threads about this, but NONE of them seem to work for me, and my particular case.

I have a tab bar 5 items, and I want the central item (index 2) to be a different colour when UNSELECTED. I don't care if the text is original colour, nor do I care about the colour when it is selected.

Here is the twist; I am using the 'Images' assets to provide the icon for the tab bar, it seems if I don't use the assets all my tab bar icons are pixelated. Plus, when creating the tab bar controller, it said to use image assets.

Can anyone shed some light on me? Thank you.

È stato utile?

Soluzione

What I ended up doing : I created a custom UITabBarItem class.

@interface MyTabBarItem : UITabBarItem

- (void)setColor:(UIColor *)color forState:(UIControlState)state;

@end

And it's implementation :

- (void)setColor:(UIColor *)color forState:(UIControlState)state {
    NSMutableDictionary *attributes = [[self titleTextAttributesForState:state] mutableCopy];
    if (!attributes) {
        attributes = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    attributes[NSForegroundColorAttributeName] = color;
    [self setTitleTextAttributes:attributes forState:state];

    UIImage *image = [[self tintImage:self.image WithColor:color] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    if (state == UIControlStateSelected) {
        self.selectedImage = image;
    } else {
        self.image = image;
    }
}

- (UIImage *)tintImage:(UIImage *)image WithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(image.size, NO, [[UIScreen mainScreen] scale]);
    CGRect drawRect = CGRectMake(0, 0, image.size.width, image.size.height);
    [image drawInRect:drawRect];
    [tintColor set];
    UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceAtop);
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tintedImage;
}

So, each button can be set up independently. Each of you button is setUp with setColor:forState:UIControlStateNormal and setColor:forState:UIControlStateSelected

And voilà! (Works for iOS 7 min)

Altri suggerimenti

Put this in your ViewController's viewDidLoad:

[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1 green:1 blue:1 alpha:1]
                                                } forState:UIControlStateNormal];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top