Search code examples
multidimensional-arrayswiftuiswiftui-foreach

SwiftUI Strange results with nested Foreach loops with LazyVGrid


From a lot of comments it is well known, that nested Foreach loops sometimes don't work as expected. However, up to now I didn't find a solution for the problem. The code example should produce a vie with the content

ad   ae   af
bd   be   bf

However, only the first line is displayed. The reason is quite clear formulated by the error messages:

LazyVGridLayout: the ID d is used by multiple child views, this will give undefined results! LazyVGridLayout: the ID e is used by multiple child views, this will give undefined results! LazyVGridLayout: the ID f is used by multiple child views, this will give undefined results!

Does somebody know how to solve the problem?

struct ContentView: View {
    let rowData = ["a", "b"]
    let colData = ["d", "e", "f"]
    let colums = [GridItem(), GridItem(), GridItem()]
    
    var body: some View {
        LazyVGrid(columns: colums) {
            ForEach(rowData, id: \.self) { rowItem in

                ForEach(colData, id: \.self) {colItem in
                    Text(rowItem + colItem)
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Solution

  • The LazyVGrid layout is getting confused with the ID of the Views it is presenting.

    So give it a unique id for each Text view. Like this:

     Text(rowItem + colItem).id(rowItem + colItem)
    

    Works for me.