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
相关产品推荐
相关产品推荐

