iOS导航栏左侧返回按钮返回时字体闪烁问题排查
问题原因及解决方法
这个问题的核心是全局外观设置没有覆盖导航栏过渡/返回时的系统默认样式,尤其是iOS 13+引入UINavigationBarAppearance后,旧的UIBarButtonItem.appearance()设置无法完全覆盖所有场景,导致返回时短暂显示系统默认字体。
解决步骤
1. 使用UINavigationBarAppearance统一配置(推荐,适配iOS13+)
直接针对导航栏的外观进行全局设置,覆盖包括返回按钮在内的所有导航栏控件样式:
// 创建导航栏外观配置 let navBarAppearance = UINavigationBarAppearance() // 设置导航栏标题字体(按需配置) navBarAppearance.titleTextAttributes = [ NSAttributedString.Key.font: AppTheme.ptsansMedium(withSize: 17.0), NSAttributedString.Key.foregroundColor: currentTheme.mainColor ] // 设置导航栏按钮(含返回按钮、自定义按钮)的字体 navBarAppearance.buttonAppearance.normal.titleTextAttributes = [ NSAttributedString.Key.font: AppTheme.ptsansMedium(withSize: 17.0), NSAttributedString.Key.foregroundColor: currentTheme.mainColor ] // 同步所有状态的样式 navBarAppearance.buttonAppearance.highlighted.titleTextAttributes = navBarAppearance.buttonAppearance.normal.titleTextAttributes navBarAppearance.buttonAppearance.focused.titleTextAttributes = navBarAppearance.buttonAppearance.normal.titleTextAttributes navBarAppearance.buttonAppearance.disabled.titleTextAttributes = navBarAppearance.buttonAppearance.normal.titleTextAttributes // 应用全局导航栏外观 UINavigationBar.appearance().standardAppearance = navBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance // 滚动到顶部时的外观 UINavigationBar.appearance().compactAppearance = navBarAppearance // 紧凑布局时的外观
2. 补充覆盖UIBarButtonItem的所有状态(兼容旧方式)
如果坚持使用旧的UIBarButtonItem.appearance()方式,需要补充设置disabled状态,并确保导航栏返回按钮样式被覆盖:
let textAttributes = [ NSAttributedString.Key.font: AppTheme.ptsansMedium(withSize: 17.0), NSAttributedString.Key.foregroundColor: currentTheme.mainColor ] // 覆盖UIBarButtonItem的所有状态 UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, for: .normal) UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, for: .focused) UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, for: .highlighted) UIBarButtonItem.appearance().setTitleTextAttributes(textAttributes, for: .disabled) // 单独设置导航栏内返回按钮的样式 UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(textAttributes, for: .normal)
问题根源
- 原代码只覆盖了
normal、focused、highlighted三种状态,遗漏了disabled状态,而返回过渡过程中系统可能短暂触发该状态。 - iOS13+的导航栏使用
UINavigationBarAppearance管理样式,旧的UIBarButtonItem.appearance()设置无法完全覆盖导航栏内部控件的过渡样式,导致默认字体短暂显示。
内容的提问来源于stack exchange,提问作者Felipe Peña
相关产品推荐
相关产品推荐

