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

SwiftUI中GridLayout无法渲染网格问题求助

GridLayout 未生成网格布局,呈现 VStack 效果的解决方案

核心问题:GridLayout是Layout协议的实现类型,并非直接可用的容器视图,直接以容器方式调用不会生效,需通过AnyLayout或显式布局方法应用其规则。

修正代码(适配AnyLayout协议要求)

struct ContentView: View {
    var body: some View {
        AnyLayout(GridLayout(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10)) {
            ForEach(0..<10) { _ in
                Rectangle()
                    .aspectRatio(1, contentMode: .fit)
                    .frame(idealHeight: 40)
                    .foregroundColor(.red)
            }
        }
        .frame(maxWidth: .infinity)
    }
}

补充说明

  • 若无需动态切换布局,也可直接使用layout(_:)方法绑定布局规则:
struct ContentView: View {
    let gridLayout = GridLayout(alignment: .leading, horizontalSpacing: 10, verticalSpacing: 10)
    
    var body: some View {
        ForEach(0..<10) { _ in
            Rectangle()
                .aspectRatio(1, contentMode: .fit)
                .frame(idealHeight: 40)
                .foregroundColor(.red)
        }
        .layout(gridLayout)
        .frame(maxWidth: .infinity)
    }
}

两种方式均能让GridLayout的网格布局规则生效,替代原本的垂直堆叠效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:45:02