将 LazyVGrid 分解成多个部分

Break a LazyVGrid into pieces

我使用以下代码在 SwiftUI 中创建了以下网格:

let columnGrid = [GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0),
                                  GridItem(.fixed(boxWidth), spacing: 0)]

LazyVGrid(columns: columnGrid, spacing: 0) {
                        ForEach((0...80), id: \.self) {
                            Text("\(positions[[=10=]])")
                                .font(.system(size: 27))
                                .frame(width: boxWidth, height: boxWidth)
                                .background(Rectangle().stroke(lineWidth: 0.5))
                        }
                    }

如何将网格分解成碎片?例如,将网格分成 4 个块的组。

a b     e g     i j
c d     f h     k l

m n     q r
o p     s t

等等

每次我尝试组合 LazyVGrid 或大量 HStacks 和 VStacks 时,它看起来都非常臃肿。

我也尝试过固定 headers 部分,但它只能将内容分成几行。我希望它分成行和列。

在 SwiftUI 中有没有一种简单的方法可以做到这一点?

您真正想要做的是将网格置于网格内。对于您演示的输出,您需要 LazyVGrid inside of a LazyHGrid。最困难的部分是分块数据,而不是视图本身。可以这样实现,例如:

struct LazyVGridInLazyHGridView: View {
    
    @StateObject var vm = LazyVGridInLazyVGridViewModel()
    
    let gridsColumn = [GridItem(.flexible(), spacing: 0), GridItem(.flexible(), spacing: 0)]
    let boxColumn = [GridItem(.fixed(30), spacing: 0), GridItem(.fixed(30), spacing: 0)]
    
    var body: some View {
        LazyHGrid(rows: gridsColumn, spacing: 15) {
            ForEach(vm.data, id: \.self) { box in
                LazyVGrid(columns: boxColumn, spacing: 15) {
                    ForEach(box) { item in
                        Text(item.name)
                    }
                }
                .background(Color.gray.opacity(0.15))
            }
        }
        .frame(height: 150)
    }
}

struct VGridDataModel: Identifiable, Hashable {
    let id = UUID()
    var name: String
}

class LazyVGridInLazyVGridViewModel: ObservableObject {
    @Published var data: [[VGridDataModel]] = []
    
    init() {
        for strideIndex in stride(from: 1, to: 20, by: 4) {
            data.append(Array(strideIndex..<(strideIndex + 4)).map({ VGridDataModel(name: [=10=].description) } ))
        }
    }
}