Search code examples
swiftuiforeachnested

How to manage Int range used in nested ForEach loop based on higher ForEach loop


I'd like to show HexagonView via two nested ForEach loops like shown in code below

ForEach(1...7, id: \.self) { row in
    VStack {
        HStack {
            ForEach(1...row, id: \.self) { col in
                HexagonView(center: CGPoint(x: getX(...), y: getY(...)), radius: 25)
            }               
        }
    }
}

Final look should be like triangle from little hexagons (first row 1 hexagon, second row two, third row three hexagons, etc.) but it looks weird on the screen even if centers of each hexagons seems to be calculated correctly. My suspicion is that using of row as upper bound of nested range is the issue. What better approach I could use?


Solution

  • Though @loremipsum is right, in your case you just have to move the VStack above the first ForEach:

            VStack { // here
                ForEach(1...7, id: \.self) { row in
                    HStack {
                        ForEach(1...row, id: \.self) { col in
                            Image(systemName: "hexagon")
                        }
                    }
                }
            }
    

    enter image description here