【发布时间】:2010-10-21 21:40:12
【问题描述】:
我需要将 UITabBar 的选择颜色从默认的蓝色更改为红色。我们如何做到这一点。
【问题讨论】:
标签: ios iphone objective-c cocoa-touch uitabbar
我需要将 UITabBar 的选择颜色从默认的蓝色更改为红色。我们如何做到这一点。
【问题讨论】:
标签: ios iphone objective-c cocoa-touch uitabbar
2017 年 9 月更新: 我写这个答案已经两年了,因为它经常收到支持,我应该说这可能是这个问题的最糟糕的答案,它容易出错,可能由于 iOS 更新而中断,难以调试等。 ,所以请不要做我写的事情并应用更好的解决方案,例如子类化 UITabBar 或 UITabBarController。谢谢。
您可以通过为您的 UITabBar 设置“tintColor”属性(键路径)来做到这一点。
应该这样做。您可以对照下面的屏幕截图进行检查。
更多信息: UITabBar 的 Identity Inspector 中有一个“Tint”属性,我相信它会做同样的事情,但显然,它什么也没做。它的默认值是选择 UITabBarItem 时的确切默认填充颜色,所以我猜它会在稳定版本 Xcode 7 中修复。手指交叉。
【讨论】:
在 IOS5 中,UITabBar 有一个 selectedImageTintColor 属性,可以满足您的需要。
【讨论】:
在 iOS 7 中,它只是 tintColor。实现此目的的一种方法是继承 UITabBarViewController,在情节提要中设置自定义类,然后在子类 tabBarVC 的 viewDidLoad 方法中添加:
[[self tabBar] setTintColor:[UIColor redColor]];
【讨论】:
unselectedItemTintColor
非常简单
创建一个 UITabBarController 的自定义类,并在 -(void)viewDidLoad 方法中添加这一行:
[[self tabBar] setSelectedImageTintColor:[UIColor greenColor]];
【讨论】:
因为 UITextAttributeTextColor 在 iOS 7 中已被弃用,你应该使用:
[UITabBarItem.appearance setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor greenColor]} forState:UIControlStateNormal];
[UITabBarItem.appearance setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor purpleColor]} forState:UIControlStateSelected];
【讨论】:
从 iOS 8 开始,就这么简单:
UITabBar.appearance().tintColor = UIColor.redColor()
【讨论】:
只需在 Interface Builder 中为 TabBar 更改以下属性
显然在我的情况下它是白色的。
【讨论】:
SDK 并不容易,但技术上 是可行的。 Apple 显然认为这是他们对一致外观和感觉的愿景的一部分。
UITabBar 是 UIView 的子类。你总是可以继承并实现你自己的-drawRect:
这不是一项简单的任务,但是,您必须从头开始重新实现该类,否则可能会产生一些奇怪的副作用。
【讨论】:
在 Swift 5 中这很容易。
在您的TabBarController 中写下:
tintColor = UIColor.red
就是这样
【讨论】:
我一直在寻找一种方法来设置 UITabBarItem 的选定文本颜色,并找到了一个非常简单的方法,使用 UIAppearance 协议。
[UITabBarItem.appearance setTitleTextAttributes:@{
UITextAttributeTextColor : [UIColor greenColor] } forState:UIControlStateNormal];
[UITabBarItem.appearance setTitleTextAttributes:@{
UITextAttributeTextColor : [UIColor purpleColor] } forState:UIControlStateSelected];
请原谅可怕的颜色!
【讨论】:
iOS 5.0 修复了此问题,但该解决方案受保密协议约束。在您的文档中查找 UITabBar 以获得一种简单的方法来做您想做的事情。
【讨论】: