setTintColor和setSelectedImageTintColor无法正常工作

时间:2015-06-25 06:32:57

标签: ios objective-c uitabbar uitabbaritem

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

setSelectedImageTintColorsetTintColor无法合作。

如果该代码顺序是

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

然后输出

enter image description here

如果该代码顺序是

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

然后输出

enter image description here

我在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]];

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

感谢您的期待。

1 个答案:

答案 0 :(得分:6)

首先,从iOS 8.0开始,selectedImageTintColor已被弃用。

我设法实现您想要的唯一方法是为所选和未选择的状态分别设置图像,并分别使用UITabBbarItem' selectedImageimage属性

重要提示:默认情况下,这两个图片属性都会呈现为" templates",这意味着它们是根据源图片中的Alpha值创建的,因此会得到他们的来自tabBar的tintColor的颜色。

要防止出现这种情况,请使用UIImageRenderingModeAlwaysOriginal

提供图像

因此,为了得到你想要的东西,你需要有两个版本的所有tabbar-images,一个是红色(用于未选择状态),一个是绿色(用于选择状态),然后执行此操作:

示例(swift):

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

示例(objective-c):

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