【问题标题】:Is it possible to set individual tint colors for each button on UITabBar?是否可以为 UITabBar 上的每个按钮设置单独的色调颜色?
【发布时间】:2026-02-02 01:55:11
【问题描述】:
是否可以在标签栏上为单个UITabBarItem 设置单独的色调?我只知道如何使用[UITabBar appearance] setTintColor: 进行通用设置。但是,例如,我希望一个选项卡在选中时用蓝色着色,另一个用红色等。
我知道可以通过使用UIImageRenderingModeAlwaysOriginal 设置image 和selectedImage 属性来部分缓解这种情况,以保留原始图像颜色,但标题文本仍然具有整个标签栏的原始色调。
【问题讨论】:
标签:
ios
objective-c
cocoa-touch
uitabbar
【解决方案1】:
更改 tintColor 属性个体是不可能的,但您仍然可以更改标签栏项目的文本颜色。
例如:
[theTabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}
forState:UIControlStateNormal];
[theTabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor greenColor]}
forState:UIControlStateHighlighted];
【解决方案2】:
对于正常状态(未选中):
[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}
forState:UIControlStateNormal];
对于选定的州:
[tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]}
forState:UIControlStateHighlighted];
【解决方案3】:
改变个别的色调并非不可能,只是需要付出相当大的努力才能实现。这样做的方法是覆盖标签栏的didSelectItem 方法。当用户选择一个项目时,你将tabBar.tintColor 更改为你想要的那个项目的任何tintColor,然后必须调用selectedIndex = //The tapped index。如果你愿意,我会发布一些代码,这肯定是一个 hack
【解决方案4】:
实际上,通过一些技巧,您可以设置单个按钮的色调。
let button1 = UITabBarItem(title: "Btn1", image: UIImage(systemName: "heart"), tag: 1)
let button2 = UITabBarItem(title: "Btn2", image: UIImage(systemName: "heart"), tag: 2)
let button3 = UITabBarItem(title: "Btn3", image: UIImage(systemName: "heart"), tag: 3)
let button4 = UITabBarItem(title: "Btn4", image: UIImage(systemName: "heart"), tag: 4)
let button5 = UITabBarItem(title: "Btn5", image: UIImage(systemName: "heart"), tag: 5)
tabBar.items = [button1, button2, button3, button4, button5]
// setting tint of the button4
if let imageView = tabBar.subviews[4].subviews.first as? UIImageView {
imageView.tintColor = UIColor.red
imageView.image = UIImage(systemName: "heart.fill")
}
如果您还决定更改按钮的图像,请使用相同的 imageView 而不是 button4.image,否则其他一些随机按钮可能会更改其色调。 tabBar.subviews[0] 是栏本身的背景图像,后续子视图是您添加的按钮。每个元素都是具有两个子视图的 UITabBarButton 类型:第一个 UITabBarSwappableImageView 和第二个 UITabBarButtonLabel。