You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI List导航栏标题:修改字体与内边距并保留滚动动态效果

修改SwiftUI导航栏标题样式并保留滚动折叠特性

解决方案思路

要同时实现自定义标题字体/内边距和保留滚动时的标题折叠效果,需要通过UINavigationBarAppearance来配置导航栏样式——直接用SwiftUI原生修饰符无法兼顾两者需求。

实现步骤

  • 创建自定义UINavigationBarAppearance实例,分别配置滚动前大标题和滚动后小标题的字体、内边距。
  • 将配置好的外观同步应用到导航栏的standardAppearance、scrollEdgeAppearance和compactAppearance,确保滚动切换时样式一致且原生折叠特性不受影响。

完整代码示例

#Preview() {
    NavigationView {
        List {
            ForEach(1..<30) { number in
                Text("\(number)")
            }
            .navigationTitle("My Title")
            .onAppear {
                // 初始化导航栏外观配置
                let appearance = UINavigationBarAppearance()
                
                // 配置滚动前的大标题样式
                appearance.largeTitleTextAttributes = [
                    .font: UIFont.systemFont(ofSize: 34, weight: .heavy), // 自定义大标题字体
                    .foregroundColor: UIColor.label
                ]
                // 调整大标题内边距(水平/垂直偏移)
                appearance.largeTitlePositionAdjustment = UIOffset(horizontal: 16, vertical: 8)
                
                // 配置滚动后的小标题样式
                appearance.titleTextAttributes = [
                    .font: UIFont.systemFont(ofSize: 18, weight: .semibold), // 自定义小标题字体
                    .foregroundColor: UIColor.label
                ]
                // 调整小标题内边距
                appearance.titlePositionAdjustment = UIOffset(horizontal: 16, vertical: 0)
                
                // 应用配置到导航栏全状态
                UINavigationBar.appearance().standardAppearance = appearance
                UINavigationBar.appearance().scrollEdgeAppearance = appearance
                UINavigationBar.appearance().compactAppearance = appearance
            }
        }
    }
}

代码说明

  • largeTitleTextAttributes:控制滚动展开状态下大标题的字体、颜色等属性。
  • largeTitlePositionAdjustment:通过UIOffset调整大标题的左右/上下内边距。
  • titleTextAttributes:控制滚动折叠后小标题的样式。
  • titlePositionAdjustment:调整小标题的内边距。
  • 同步设置三种外观属性,是为了保证导航栏在静态、滚动边缘、紧凑状态下都应用自定义样式,同时完整保留原生的标题折叠动画。

内容的提问来源于stack exchange,提问作者P. Sami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 11:37:12