【问题标题】:setTintColor and setSelectedImageTintColor are not working properly togethersetTintColor 和 setSelectedImageTintColor 不能一起正常工作
【发布时间】:2015-06-25 06:32:57
【问题描述】:

我正在尝试更改我的自定义标签栏的标签栏项目的图标颜色,

但是setSelectedImageTintColorsetTintColor 不能一起工作。

如果代码顺序是

[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[[UITabBar appearance] setTintColor:[UIColor redColor]];

那么输出是

如果代码顺序是

[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];

那么输出是

我在didFinishLaunchingWithOptions 方法中使用了以下代码,前两行工作正常,问题出在最后两行

//To set color for unselected tab bar item's title color
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary  dictionaryWithObjectsAndKeys: [UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

//To set color for selected tab bar item's title color
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor greenColor], NSForegroundColorAttributeName,nil] forState:UIControlStateSelected];


//To set color for unselected icons
[[UITabBar appearance] setTintColor:[UIColor redColor]];

//To set color for selected icons
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];

注意 - 我有单独的自定义标签栏类,但我没有更改自定义标签栏类中的图标颜色

感谢期待。

【问题讨论】:

    标签: ios objective-c uitabbar uitabbaritem


    【解决方案1】:

    首先,selectedImageTintColor自 iOS 8.0 起已弃用。

    我设法实现您想要的唯一方法是为选定和未选定状态分别使用图像,并分别使用UITabBbarItemselectedImageimage 属性。

    重要提示:默认情况下,这两个图像属性都呈现为“模板”,这意味着它们是根据源图像中的 alpha 值创建的,因此会从 tabBar 的 tintColor 中获取它们的颜色.

    为防止出现这种情况,请使用UIImageRenderingModeAlwaysOriginal 提供图像。

    所以,为了得到你想要的,你需要拥有所有标签栏图像的两个版本,一个红色(用于未选择状态)和一个绿色(用于选定状态),然后执行以下操作:

    示例(快速):

        tabBarItem1.image = UIImage(named:"redHouse")?.imageWithRenderingMode(.AlwaysOriginal)
        tabBarItem1.selectedImage = UIImage(named:"greenHouse")?.imageWithRenderingMode(.AlwaysOriginal)
    

    示例(目标-c):

        [tabBarItem1 setImage:[[UIImage imageNamed:@"redHouse"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [tabBarItem2 setSelectedImage:[[UIImage imageNamed:@"greenHouse"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    

    【讨论】:

    • 首先,感谢您的回答。供您参考,我使用的是 iOS 7,如果我使用 UIImageRenderingModeAlwaysOriginal,它将始终显示原始图像,但我想更改标签栏项目的图标颜色与标签栏项目的标题颜色相同,用于选中和未选中
    • 是的,但是即使你使用 iOS7,tintColor 和 selectedImageTintColor 也不足以真正改变 unselected 状态的图标颜色。另请注意,tintColor 实际上更改了 selected 状态的标题和图标颜色。所以tintColorselectedImageTintColor 之间的唯一区别是第二个不会改变标题颜色(selected tabbarItem)
    • 我编辑了我的原始答案,所以现在我的意思可能更清楚了吗?
    • 在 iOS7 中使用 tint color 来实现这一点简直是不可能,你链接的问题给出了相同的答案。
    • @pIkEL 我们需要在程序的什么地方编写这段代码?
    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多