如何通过编程方式修改导航栏项目的字体颜色与字号?
用Swift代码修改导航栏标题的字体颜色与字号
当然可以完全通过Swift代码来修改导航栏标题的字体颜色和字号,不用依赖StoryBoard的配置。下面分两种常用场景给你具体实现代码:
1. 全局统一设置(所有导航控制器生效)
如果希望整个App的导航栏标题样式保持一致,可以在AppDelegate.swift的启动方法里配置:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 创建导航栏外观配置对象 let navBarAppearance = UINavigationBarAppearance() // 设置标题的字体和颜色,可按需调整参数 navBarAppearance.titleTextAttributes = [ .font: UIFont.systemFont(ofSize: 20, weight: .bold), // 字号20,粗体样式 .foregroundColor: UIColor.red // 标题颜色,替换成你需要的颜色值 ] // 应用配置到全局导航栏 UINavigationBar.appearance().standardAppearance = navBarAppearance // 适配滚动到顶部时的导航栏样式 UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance return true }
2. 单个视图控制器单独设置
如果只需要特定页面的导航栏标题样式不同,直接在对应VC的viewDidLoad方法里修改:
override func viewDidLoad() { super.viewDidLoad() // 定义标题的属性字典 let titleAttributes: [NSAttributedString.Key: Any] = [ // 这里可以替换成自定义字体名称,比如"PingFangSC-Semibold",找不到则 fallback 到系统字体 .font: UIFont(name: "HelveticaNeue-Bold", size: 18) ?? UIFont.systemFont(ofSize: 18), .foregroundColor: UIColor.blue // 标题颜色 ] // 应用到当前导航栏 navigationController?.navigationBar.titleTextAttributes = titleAttributes // 可选:确保滚动时样式一致 if let appearance = navigationController?.navigationBar.standardAppearance.copy() { appearance.titleTextAttributes = titleAttributes navigationController?.navigationBar.scrollEdgeAppearance = appearance } }
补充:大标题模式的适配
如果你的导航栏使用了大标题(Large Title)样式,需要修改largeTitleTextAttributes属性,示例如下:
// 全局设置时 navBarAppearance.largeTitleTextAttributes = [ .font: UIFont.systemFont(ofSize: 34, weight: .heavy), .foregroundColor: UIColor.purple ] // 单个VC设置时 navigationController?.navigationBar.largeTitleTextAttributes = [ .font: UIFont(name: "Arial-BoldMT", size: 32) ?? UIFont.systemFont(ofSize: 32), .foregroundColor: UIColor.orange ]
内容的提问来源于stack exchange,提问作者Twisha Solgama
相关产品推荐
相关产品推荐

