将单元格动态添加到 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 !!