1

如何在 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")
            }
        }
    }
}
4

1 回答 1

1

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

var body: some View {
    LazyVGrid(columns: gridLayout) {
        ForEach(counter.indices, id: \.self) { item in      // << here !!
于 2021-02-02T18:43:28.097 回答