导航栏标题:仅修改字体而不改变字号的实现方法
只修改导航栏标题字体而保留原有字号的解决方案
嘿,这个问题我之前折腾导航栏的时候也踩过坑!确实直接操作pointSize对导航栏标题不管用——因为导航栏的标题字号是系统管控的,尤其是还涉及动态类型(Dynamic Type)的适配,直接改pointSize不会生效。咱们换个思路,通过获取系统默认的标题字号,再基于这个字号创建自定义字体,就能完美实现只换字体、不碰字号的需求。
针对iOS 13+的实现(支持常规标题和大标题)
现在iOS 13及以上版本提供了专门的属性来配置常规标题和大标题的样式,咱们可以先获取系统默认的字体字号,再替换成自定义字体:
Swift 示例
// 全局配置所有导航栏(可放在AppDelegate/SceneDelegate的启动方法里) // 1. 处理常规标题 if let defaultTitleFont = UINavigationBar.appearance().titleTextAttributes?[.font] as? UIFont { // 用系统默认字号创建自定义字体 guard let customTitleFont = UIFont(name: "YourCustomFontFamily", size: defaultTitleFont.pointSize) else { // 自定义字体加载失败时, fallback 到系统默认字体 return } UINavigationBar.appearance().titleTextAttributes = [.font: customTitleFont] } // 2. 处理大标题(如果你的导航栏启用了大标题) if let defaultLargeTitleFont = UINavigationBar.appearance().largeTitleTextAttributes?[.font] as? UIFont { guard let customLargeTitleFont = UIFont(name: "YourCustomFontFamily", size: defaultLargeTitleFont.pointSize) else { return } UINavigationBar.appearance().largeTitleTextAttributes = [.font: customLargeTitleFont] }
如果只想给单个ViewController的导航栏设置,把UINavigationBar.appearance()换成self.navigationController?.navigationBar即可。
Objective-C 示例
// 全局配置常规标题 UIFont *defaultTitleFont = [[UINavigationBar appearance].titleTextAttributes objectForKey:NSFontAttributeName]; UIFont *customTitleFont = [UIFont fontWithName:@"YourCustomFontFamily" size:defaultTitleFont.pointSize]; if (customTitleFont) { [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName: customTitleFont}]; } // 全局配置大标题 UIFont *defaultLargeTitleFont = [[UINavigationBar appearance].largeTitleTextAttributes objectForKey:NSFontAttributeName]; UIFont *customLargeTitleFont = [UIFont fontWithName:@"YourCustomFontFamily" size:defaultLargeTitleFont.pointSize]; if (customLargeTitleFont) { [[UINavigationBar appearance] setLargeTitleTextAttributes:@{NSFontAttributeName: customLargeTitleFont}]; }
关键原理说明
- 导航栏的标题字号会跟随系统动态类型(比如用户在设置里调整字体大小)自动变化,直接设置固定字号会破坏这种适配性。
- 通过获取系统默认的标题字体,提取其
pointSize来创建自定义字体,既能保留系统的字号适配逻辑,又能替换成你想要的字体。 - 一定要做字体加载失败的判断,避免因为字体名称写错导致导航栏标题消失的问题。
内容的提问来源于stack exchange,提问作者CaMenz
相关产品推荐
相关产品推荐

