ios - setTintColor 和 setSelectedImageTintColor 不能一起正常工作

标签 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]];

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

感谢期待。

最佳答案

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

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

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

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

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

示例(快速):

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

关于ios - setTintColor 和 setSelectedImageTintColor 不能一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042856/

相关文章:

iphone - 如何将 exif 元数据写入图像(不是相机胶卷,只是 UIImage 或 JPEG)

ios - 在 Xcode 中创建逼真的云

ios - 如何修复 xcode 中的 Apple Mach-O 链接器错误组问题?

ios - 如何在 RootView ChildViewControllers 中隐藏 TabBar

ios - NSUserDefaults 在 iOS6 下导致异常

ios - 我可以在 iPad 上使用哪种 UIKeyboardType

ios - 如何将字符串 "$double_number"转换为 double

iPhone UISwitch 和 TableView 保存状态

iphone - 可以滚动 UITabBar 吗?

swift - 如何使用 SWRevealViewController 从 Swift 中的 UITabBarItem 打开侧边菜单