如何在 iOS 7.1 中更改 TabBar 上的图像和标签颜色?

Posted

技术标签:

【中文标题】如何在 iOS 7.1 中更改 TabBar 上的图像和标签颜色?【英文标题】:How can I change a color of image and label on UITabBar on iOS 7.1? 【发布时间】:2014-03-28 20:12:07 【问题描述】:

如何在 ios 7.1 上更改 UITabBar 上的图像和标签颜色?在 iOS 7 上,我可以通过 Tint 属性实现它。但在 iOS 7.1 上它不起作用。

【问题讨论】:

【参考方案1】:

它在 iOS 7 和 iOS 7.1 中的工作方式相同!

在 AppDelegate 中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    // Add this if you only want to change Selected Image color 
    // and/or selected image text
    [[UITabBar appearance] setTintColor:[UIColor redColor]];

    // Add this code to change StateNormal text Color,
    [UITabBarItem.appearance setTitleTextAttributes:
    @NSForegroundColorAttributeName : [UIColor greenColor] 
    forState:UIControlStateNormal];

    // then if StateSelected should be different, you should add this code
    [UITabBarItem.appearance setTitleTextAttributes:
    @NSForegroundColorAttributeName : [UIColor purpleColor] 
    forState:UIControlStateSelected];

    return YES;

在每个 ViewController 中:(如果要更改未选中的图像颜色)

- (void)viewDidLoad

    [super viewDidLoad];

    // changing the unselected image color, you should change the selected image 
    // color if you want them to be different
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"yourImage_selectedImage"]
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.tabBarItem.image = [[UIImage imageNamed:@"yourImage_image"] 
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

这段代码的线索是'UIImageRenderingModeAlwaysOriginal':

Apple 文档的渲染模式:

UIImageRenderingModeAutomatic,          // Use the default rendering mode for the context where the image is used    
UIImageRenderingModeAlwaysOriginal,     // Always draw the original image, without treating it as a template
UIImageRenderingModeAlwaysTemplate,     // Always draw the image as a template image, ignoring its color information

【讨论】:

【参考方案2】:

UITabBarItem 从未拥有tint 属性。 没有内置类曾经有过tint 属性。这里没有任何变化。

在 iOS 7 和 7.1 中,UITabBar 具有 tintColor 属性,因为它是 UIView。

【讨论】:

【参考方案3】:

这会在选择时更改图像和标签的色调。

- (void)viewDidLoad

    [super viewDidLoad];
    [[UITabBar appearance] setTintColor:[UIColor redColor]];

【讨论】:

以上是关于如何在 iOS 7.1 中更改 TabBar 上的图像和标签颜色?的主要内容,如果未能解决你的问题,请参考以下文章

当 iOS 7 上的 selectedIndex 值更改时,TabBar 消失

如何在iOS 7中更改tabBarItems的文本和图标颜色?

ios 7.1 上的 zxingwidget 构建错误

如何在 iOS 中完全自定义 TabBar

如何在 TabBar 中删除和重置顶行 - 适用于 iOS 13+

在 iOS 6 下运行时如何从 TabBar 中删除白角