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

SwiftUI中presentationDetent Sheet顶部内容不可见问题排查

解决Sheet不同Detent下GridView顶部内容可见问题

问题根源在于Sheet处于.medium尺度时,内容高度受限,再加上你给LazyVGrid设置的.padding(.top, 50),直接导致顶部内容被挤出了可视区域,同时缺少滚动容器让内容可以向上滚动查看顶部。

下面是具体的修改方案:

  1. 用ScrollView包裹LazyVGrid,让内容在高度不足时可滚动
  2. 移除冗余的Spacer,并调整安全区域适配逻辑,确保顶部内容在任何detent尺度下都能正常显示

修改后的GridView代码:

struct GridView: View {
    
    var body: some View {
        
        let columns = [
            GridItem(.flexible()),
            GridItem(.flexible())
        ]
        
        ScrollView {
            LazyVGrid(columns: columns, spacing: 2) {
                ForEach(0..<30, id: \.self) { index in
                    Circle()
                        .frame(width: 40, height: 40)
                        .overlay {
                            Text("\(index)")
                                .foregroundColor(.white)
                        }
                }
            }
            .padding(.top, 50)
            .padding(.bottom)
        }
        .safeAreaInset(edge: .top) {
            Color.clear.frame(height: 0)
        }
    }
}

如果你不想用padding,也可以在LazyVGrid最前面添加一个空白占位项来替代.padding(.top, 50),效果一致:

LazyVGrid(columns: columns, spacing: 2) {
    // 用空白占位替代padding.top,避免内容被裁切
    Color.clear.frame(height: 50)
    ForEach(0..<30, id: \.self) { index in
        Circle()
            .frame(width: 40, height: 40)
            .overlay {
                Text("\(index)")
                    .foregroundColor(.white)
            }
    }
}

经过调整后,无论Sheet是.medium还是.large尺度,GridView的顶部内容(包括索引0的圆圈)都能通过滚动或直接显示的方式被看到,不会因高度受限被遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:48:20