如何正确设置UIKit中导航控制器的标题字体大小?
解决UIKit导航栏标题切换时字体闪烁的问题
问题分析
你遇到的是导航栏样式设置时机滞后的问题:视图控制器显示后才完成样式更新,导致默认字体先出现再切换到目标样式;跨控制器跳转或返回时,重复设置的时机不对也会触发这个闪烁现象。
解决方案
1. 用导航控制器代理提前配置(推荐)
在导航控制器的willShow代理方法中设置样式,确保控制器显示前样式已生效:
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { // 统一配置导航栏基础样式 navigationController.navigationBar.setBackgroundImage(nil, for: .default) navigationController.navigationBar.shadowImage = nil navigationController.navigationBar.barTintColor = .sBlue navigationController.navigationBar.isTranslucent = false // 设置标题字体与颜色 if let font = UIFont(name: "Roboto-Regular", size: 30) { navigationController.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white ] } }
注意:要将导航控制器的delegate属性赋值给实现该代理方法的类(比如根控制器)。
2. 全局统一配置(适用于所有页面样式相同的场景)
在App启动时一次性设置全局导航栏样式,无需在每个控制器重复编写代码:
// 在AppDelegate的application(_:didFinishLaunchingWithOptions:)中添加 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let navBarAppearance = UINavigationBar.appearance() navBarAppearance.setBackgroundImage(nil, for: .default) navBarAppearance.shadowImage = nil navBarAppearance.barTintColor = .sBlue navBarAppearance.isTranslucent = false if let font = UIFont(name: "Roboto-Regular", size: 30) { navBarAppearance.titleTextAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white ] } return true }
3. 针对差异化样式,提前在viewWillAppear设置
如果不同控制器需要不同的导航栏样式,在viewWillAppear中先完成样式设置,再调用super方法:
override func viewWillAppear(_ animated: Bool) { // 先配置导航栏样式 if let font = UIFont(name: "Roboto-Regular", size: 30) { navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white ] } navigationController?.navigationBar.setBackgroundImage(nil, for: .default) navigationController?.navigationBar.shadowImage = nil navigationController?.navigationBar.barTintColor = .sBlue navigationController?.navigationBar.isTranslucent = false super.viewWillAppear(animated) }
额外提示
- 确认"Roboto-Regular"字体已正确导入项目(添加到Info.plist的
Fonts provided by application数组中),避免因字体缺失使用默认样式。 - 如果使用了大标题(Large Title),需额外配置
largeTitleTextAttributes:
navigationController?.navigationBar.largeTitleTextAttributes = [ NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.white ]
内容的提问来源于stack exchange,提问作者Car Lord VR
相关产品推荐
相关产品推荐

