自定义UINavigationController:导航栏标题颜色修改问题
嘿,我之前做项目的时候也踩过这个一模一样的坑!Bar tint和tint color都能正常修改,偏偏标题颜色死活不生效,大概率是这几个原因之一,给你捋捋解决方案:
1. 检查titleTextAttributes的完整赋值
看你代码里只写了navigationBar.titleTextAttributes =...,后面的内容没贴全,大概率是没正确设置foregroundColor属性。要确保用的是NSAttributedString.Key.foregroundColor这个键,而不是旧的字符串常量,示例代码如下:
func setupAppearance() { navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.orange, // 替换成你需要的颜色 // 可选:顺便配置标题字体 NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18, weight: .semibold) ] // 你的其他设置 navigationBar.barTintColor = UIColor.white navigationBar.tintColor = UIColor.blue navigationBar.isTranslucent = false }
2. 开启大标题(Large Title)时要单独配置
如果你的导航栏开启了prefersLargeTitles = true,普通的titleTextAttributes只对小尺寸标题生效,大标题的颜色需要单独设置largeTitleTextAttributes:
func setupAppearance() { // 常规小标题样式 navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange] // 大标题样式 navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.orange] navigationBar.prefersLargeTitles = true // 如果你启用了大标题 }
3. iOS 13+ 优先用新的UINavigationBarAppearance API
iOS 13之后苹果推出了更统一的外观配置方案,旧的titleTextAttributes可能会被新的Appearance设置覆盖,推荐用这种方式全局配置:
func setupAppearance() { let navAppearance = UINavigationBarAppearance() // 配置不透明背景(对应isTranslucent = false) navAppearance.configureWithOpaqueBackground() navAppearance.backgroundColor = UIColor.white // 对应barTintColor // 设置标题颜色 navAppearance.titleTextAttributes = [.foregroundColor: UIColor.orange] // 大标题颜色(如果启用的话) navAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.orange] // 将外观应用到所有场景 navigationBar.standardAppearance = navAppearance navigationBar.scrollEdgeAppearance = navAppearance // 滚动到顶部时的样式 navigationBar.compactAppearance = navAppearance // 横屏等紧凑场景 navigationBar.tintColor = UIColor.blue navigationBar.isTranslucent = false }
4. 排查是否被单个ViewController的局部设置覆盖
如果某个ViewController里自己设置了navigationItem.titleTextAttributes,或者用了自定义的titleView,会直接覆盖导航控制器的全局配置,记得检查这些地方有没有冲突。
试试上面的方法,应该能解决你的问题!
内容的提问来源于stack exchange,提问作者Lachtan
相关产品推荐
相关产品推荐

