UINavigationBar返回根控制器后标题颜色仍为白色的问题
导航栏标题颜色未恢复的原因与修复方案
问题根源
兄弟,这个问题我太熟了!你现在的问题出在导航栏标题文字颜色的控制逻辑上——你只设置了导航栏的背景、按钮颜色和状态栏样式,但标题文字的颜色是由单独的属性控制的,你在返回时没重置它,所以标题还停留在白色。
具体来说:
- 你用的
barStyle = .black只是间接让标题变成白色(系统默认在黑色barStyle下标题为白色),但没有显式绑定; tintColor管的是返回按钮、右侧按钮这些交互控件,并不影响标题文字;- 真正控制标题颜色的是
navigationBar.titleTextAttributes这个字典,你在viewWillAppear里没显式设置它,返回时也没把它改回黑色,所以标题颜色就“卡住”在白色了。
修复代码
把你的代码补上标题颜色的设置和重置就行,修改后的代码如下:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 保持你原来的导航栏透明配置 navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.barStyle = .black navigationController?.navigationBar.tintColor = .white navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.backgroundColor = .clear navigationController?.view.backgroundColor = .clear // 显式设置标题为白色 navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] setNeedsStatusBarAppearanceUpdate() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // 保持你原来的导航栏恢复配置 navigationController?.navigationBar.shadowImage = nil navigationController?.navigationBar.barStyle = .default navigationController?.navigationBar.tintColor = .black navigationController?.navigationBar.setBackgroundImage(nil, for: .default) navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.backgroundColor = .white navigationController?.view.backgroundColor = .white // 重置标题为黑色(或者用系统默认颜色,把值改成nil也可以) navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black] setNeedsStatusBarAppearanceUpdate() }
额外小贴士
如果你的项目里有很多地方需要切换导航栏样式,建议封装一个导航栏样式管理的工具类,避免每个VC都写重复代码,也能减少这类遗漏属性的问题。
内容的提问来源于stack exchange,提问作者Tometoyou
相关产品推荐
相关产品推荐

