动态添加单元格到 SwiftUI LazyGrid

Dynamically add cells to SwiftUI LazyGrid

如何在 SwiftUI 中动态添加单元格(不是列)到某些 LazyVGrid? 以下代码应通过单击按钮添加 1 个单元格。它编译但不起作用。 我少了什么?

import SwiftUI

struct GridContent: Identifiable {
    var id = UUID()
}

struct ContentView: View {

    @State var counter = [ GridContent() ]
    var gridLayout = [ GridItem() ]
       
    var body: some View {
        LazyVGrid(columns: gridLayout) {
            ForEach(counter.indices) { item in
                Text("\(item)")
            }
            Button(action: {
                counter.append(GridContent())
            }) {
                Image(systemName: "plus.circle.fill")
            }
        }
    }
}

在这种情况下,您应该使用 ForEach 的动态变体,例如

var body: some View {
    LazyVGrid(columns: gridLayout) {
        ForEach(counter.indices, id: \.self) { item in      // << here !!