1

How to dynamically add cells (not columns) to some LazyVGrid in SwiftUI? The following code should add 1 cell by clicking the button. It compiles but doesn't work. What I a missing?

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")
            }
        }
    }
}

1 Answers1

1

You should use dynamic variant of ForEach in this case, like

var body: some View {
    LazyVGrid(columns: gridLayout) {
        ForEach(counter.indices, id: \.self) { item in      // << here !!
Asperi
  • 228,894
  • 20
  • 464
  • 690