Swift 5下无法修改Navigation Bar tint color问题求助
解决Swift中单个页面导航栏Bar Tint颜色不生效的问题
这问题我之前也碰到过!iOS 13之后苹果引入了UINavigationBarAppearance这个新API,用来统一管理导航栏的样式——如果你是通过全局设置(比如Storyboard里给Navigation Controller统一设了橙色,或者在App/SceneDelegate里用UINavigationBar.appearance()设置了全局样式),那直接在viewDidLoad里修改barTintColor的旧方法会被全局的Appearance覆盖,自然看不到红色。
下面给你两种针对性的解决方案:
方案一:使用新的Appearance API(推荐,适配iOS13+)
在你的特殊页面里,通过创建自定义的UINavigationBarAppearance实例来覆盖全局样式,代码建议放在viewWillAppear里(比viewDidLoad时机更合适,确保导航栏已经初始化完成):
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 创建自定义外观实例 let customAppearance = UINavigationBarAppearance() customAppearance.backgroundColor = .red // 设置你需要的动态颜色 // 如果需要保留标题样式,可以在这里补充设置,比如: // customAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] // 应用到导航栏的标准样式和滚动边缘样式(如果用了大标题) navigationController?.navigationBar.standardAppearance = customAppearance navigationController?.navigationBar.scrollEdgeAppearance = customAppearance }
如果希望离开这个页面后恢复原来的橙色导航栏,还可以在viewWillDisappear里重置样式:
override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // 恢复全局的橙色样式 let defaultAppearance = UINavigationBarAppearance() defaultAppearance.backgroundColor = .orange navigationController?.navigationBar.standardAppearance = defaultAppearance navigationController?.navigationBar.scrollEdgeAppearance = defaultAppearance }
方案二:禁用全局样式的优先级(适合简单场景)
如果你没有用大标题,也不想用Appearance API,可以尝试强制关闭导航栏的半透明属性,同时确保设置时机正确:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barTintColor = .red }
注意:如果你的全局设置是通过Storyboard给Navigation Controller设置的,这个方法可能偶尔还是会有延迟,所以更推荐方案一。
额外排查点
- 检查是否在其他地方(比如父类、全局工具类)有覆盖导航栏样式的代码;
- 如果用了
UINavigationController的子类,确认子类没有重写导航栏的样式设置逻辑。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

