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

如何防止LazyVStack内容滚动到透明固定Section Header下方

解决LazyVStack固定透明Section Header与内容重叠的问题

要实现透明背景的固定Section Header,同时避免内容滚动到Header后方重叠,可以通过裁剪内容区域的方式解决,具体步骤如下:

  1. 动态获取固定Header的高度
  2. 对内容区域进行顶部裁剪,裁剪高度与Header高度一致,确保内容不会进入Header的显示范围

修改后的完整代码

struct ContentView: View {
    @State private var headerHeight: CGFloat = 0
    
    var body: some View {
        ScrollView {
            LazyVStack(alignment: .leading, pinnedViews: [.sectionHeaders]) {
                Section(header:
                    Rectangle()
                        .frame(height: 300)
                        .foregroundStyle(.red)
                        .zIndex(-1)
                ) {
                    LazyVStack(alignment: .leading, pinnedViews: [.sectionHeaders]) {
                        Section(header:
                            Text("Header")
                                .font(.largeTitle)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                // 动态获取Header高度
                                .background(
                                    GeometryReader { proxy in
                                        Color.clear
                                            .onAppear {
                                                headerHeight = proxy.size.height
                                            }
                                    }
                                )
                                .background(.clear) // 保持Header背景透明
                        ) {
                            ForEach(0..<30) { item in
                                Text("Item \(item)")
                            }
                        }
                    }
                    // 裁剪内容顶部,避免内容滚动到Header后方
                    .clipShape(Rectangle().inset(by: EdgeInsets(top: headerHeight, leading: 0, bottom: 0, trailing: 0)))
                }
            }
        }
        .scrollIndicators(.never)
        .font(.title2)
        .padding()
    }
}

代码说明

  • @State private var headerHeight:用于存储固定Header的实际高度
  • GeometryReader:在Header的背景中添加该视图,获取Header的尺寸并赋值给headerHeight
  • .clipShape(Rectangle().inset(by: ...)):对内容区域进行顶部裁剪,裁剪高度等于Header高度,这样内容滚动时不会进入Header的显示区域,彻底避免重叠

内容的提问来源于stack exchange,提问作者Jaseel.Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:48:17