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

SwiftUI Section Header无法固定:代码无效果求助

解决SwiftUI滚动时Section Header无法固定的问题

你的问题出在错误地将LazyVStack嵌套在List内部:

  • List本身自带Section Header固定能力,不需要依赖LazyVStack的pinnedViews参数
  • LazyVStack的pinnedViews仅对自身内部的Section生效,无法作用于List的Section

下面提供两种可行的解决方案:

方案一:直接使用List原生的固定Header(推荐)

List的.plain样式默认支持Section Header固定,只需调整代码结构,移除多余的LazyVStack:

var body: some View {
    NavigationSplitView {
        List {
            ForEach(searchDates, id: \.self) { date in
                Section(header: Text(date)) {
                    ReceiptSection(searchResults: searchResults, date: date)
                }
            }
            .onDelete(perform: deleteItems)
        }
        .listStyle(.plain) // 显式设置plain样式,确保Header固定生效
    }
}

注意:如果使用.insetGrouped等其他List样式,Section Header不会固定,所以需要切换为.plain或.grouped(部分iOS版本下.grouped也支持固定)。

方案二:用ScrollView+LazyVStack实现固定Header(适合自定义场景)

如果需要完全自定义滚动容器,可直接用ScrollView包裹LazyVStack,此时pinnedViews参数会正常生效,但需要自行处理Header样式和交互:

var body: some View {
    NavigationSplitView {
        ScrollView {
            LazyVStack(pinnedViews: .sectionHeaders) {
                ForEach(searchDates, id: \.self) { date in
                    Section(
                        header: Text(date)
                            .background(Color(UIColor.systemBackground)) // 防止内容穿透Header
                            .padding(.vertical, 8)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    ) {
                        ReceiptSection(searchResults: searchResults, date: date)
                    }
                }
                // 注意:ScrollView不支持List的原生onDelete,需自行实现删除交互
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者David L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:15:59