如何将UITabBarController未选中项文字颜色改为选中项的白色?
修改UITabBarController未选中项文字颜色为白色的几种实用方案
嘿,刚好我之前做项目也碰到过这个需求,给你几个简单靠谱的实现方案,都是原生方法,不用折腾第三方~
方案一:直接利用UITabBar的原生属性(iOS 10+ 推荐)
从iOS 10开始,苹果给UITabBar加了unselectedItemTintColor这个属性,直接设置就能一键把未选中的文字(包括图标)改成白色,超省心:
Swift 代码:
// 可以在你的UITabBarController子类的viewDidLoad里设置,或者App启动时全局配置 tabBar.unselectedItemTintColor = .white
Objective-C 代码:
// 同样在合适的位置(比如UITabBarController的viewDidLoad)设置 self.tabBar.unselectedItemTintColor = [UIColor whiteColor];
这个方法最简洁,而且连未选中的图标颜色也会一起改成白色,如果你的图标是模板图(template image)的话效果刚好。
方案二:给单个UITabBarItem设置文字属性(兼容iOS 9及以下)
如果需要兼容更低版本的系统,就需要给每个TabBarItem单独设置文字的颜色属性:
Swift 代码:
override func viewDidLoad() { super.viewDidLoad() // 遍历所有tabBarItem,分别设置选中和未选中状态的文字颜色 tabBar.items?.forEach { item in item.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal) item.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected) } }
Objective-C 代码:
- (void)viewDidLoad { [super viewDidLoad]; for (UITabBarItem *item in self.tabBar.items) { [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal]; [item setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected]; } }
这种方法可以精准控制每个item的文字样式,甚至给不同item设置不同颜色(不过你这里需求是统一白色,所以直接循环设置就行)。
方案三:全局统一配置(整个App所有TabBar生效)
如果你的App里有多个UITabBarController,想要统一所有未选中文字为白色,可以用UIAppearance做全局设置,在App启动时配置一次就够了:
Swift 代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // iOS 10+ 全局设置未选中颜色 UITabBar.appearance().unselectedItemTintColor = .white // 兼容低版本的全局文字设置 UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected) return true }
Objective-C 代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // iOS 10+ 全局设置未选中颜色 [[UITabBar appearance] setUnselectedItemTintColor:[UIColor whiteColor]]; // 兼容低版本的全局文字设置 [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal]; [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateSelected]; return YES; }
小提醒
- 如果你的TabBar用了深色背景,白色文字刚好能保证可读性;如果是浅色背景,记得调整颜色避免看不清。
- 如果你用了第三方的TabBar框架,可能需要查看框架的自定义API,但原生方案在绝大多数场景下都能满足需求。
内容的提问来源于stack exchange,提问作者user8202800
相关产品推荐
相关产品推荐

