You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:20:24