Xcode 13中UINavigationBar的setBarTintColor方法失效及导航栏颜色异常问题求助
我前阵子刚踩过这个坑!Xcode 13对应的iOS 15+版本里,Apple对UINavigationBar的外观配置逻辑做了重大调整,原来直接修改导航栏外观属性的老方法会和新的外观系统冲突,导致你遇到的透明、元素不显示问题。
问题根源
你之前用的setBarTintColor、setTranslucent:NO这类旧API,在iOS 15+上会和新的UINavigationBarAppearance系统产生冲突。现在Apple官方推荐用新的外观配置类来统一管理导航栏的所有状态样式,包括普通状态、滚动到顶部的状态、紧凑布局状态,这样能避免样式混乱。
Objective-C 解决方案
直接替换你原来的所有导航栏外观配置代码,改用UINavigationBarAppearance来实现:
// 1. 创建导航栏外观配置实例 UINavigationBarAppearance *navAppearance = [[UINavigationBarAppearance alloc] init]; // 2. 设置背景色(对应你原来的barTintColor) [navAppearance setBackgroundColor:[UIColor AppThemeColour]]; // 3. 设置导航栏交互元素的颜色(返回按钮、右侧按钮等,对应原来的tintColor) [navAppearance setTintColor:[UIColor whiteColor]]; // 4. 配置标题样式,确保标题颜色正常显示(这一步是解决标题不显示的关键) navAppearance.titleTextAttributes = @{ NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont systemFontOfSize:17 weight:UIFontWeightMedium] // 可选,根据需求调整字体 }; // 5. 移除导航栏底部的阴影(对应你原来的shadowImage设置) [navAppearance setShadowImage:[[UIImage alloc] init]]; [navAppearance setShadowColor:nil]; // 6. 将配置应用到导航栏的所有场景,避免不同状态下样式突变 [[UINavigationBar appearance] setStandardAppearance:navAppearance]; [[UINavigationBar appearance] setScrollEdgeAppearance:navAppearance]; // 适配页面滚动到顶部时的样式 [[UINavigationBar appearance] setCompactAppearance:navAppearance]; // 适配横屏等紧凑布局场景
注意事项
- 删掉原来的
setBarTintColor、setTranslucent:NO、setShadowImage以及单独设置backgroundColor的代码,新配置已经完全覆盖了这些逻辑。 - 如果项目里有自定义导航栏子类,也可以直接在子类内部应用这个配置,不用依赖全局
appearance设置。
这样调整后,导航栏的背景色、标题和图标颜色就都能正常显示,不会再出现透明的问题了。
内容的提问来源于stack exchange,提问作者Naresh
相关产品推荐
相关产品推荐

