SwiftUI中如何将navigationTitle的字体大小改为.footnote?
SwiftUI的navigationTitle默认使用系统预设的导航栏标题样式,无法直接通过参数调整字体大小。要实现将标题设为.footnote字号,需要自定义导航栏的标题视图,以下是两种可行方案:
方案1:iOS 16+ 原生适配
利用iOS 16新增的ToolbarItem的principal位置,直接替换系统默认标题:
var body: some View { NavigationView { List { CoverImageView() .frame(height: 300) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) } .listStyle(PlainListStyle()) // 移除原navigationTitle,替换为自定义标题 .toolbar { ToolbarItem(placement: .principal) { Text("Title") .font(.footnote) // 设置为footnote字号 } } } }
方案2:兼容iOS 15及以下版本
先将导航栏标题设为行内模式,再通过自定义视图替换默认标题:
var body: some View { NavigationView { List { CoverImageView() .frame(height: 300) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) } .listStyle(PlainListStyle()) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .principal) { Text("Title") .font(.footnote) } } } }
注意事项
- 自定义标题后,系统默认的大标题缩放交互会失效;若需保留该特性,可结合
navigationBarTitleDisplayMode(.large)调整自定义视图的字体适配逻辑。 - 如需全局统一设置导航栏标题字体,可通过
UITextAppearance修改UIKit底层样式,但会影响所有页面的导航栏标题。
内容的提问来源于stack exchange,提问作者Gaurang Patel
相关产品推荐
相关产品推荐

