Search code examples
swiftuilazyvgrid

Dynamically add cells to SwiftUI LazyGrid


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

Solution

  • 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 !!