0

I am attempting to show a 3 x 3 grid of squares leveraging off of GridItem(.flexible())s ability to automatically calculate the cell width. How can I keep the existing cols defined as it is and get each cell’s height to match its width AND for the grid to layout without overlapping? I’ve reviewed many similar answers but haven’t found one that specifically addresses these concerns.

struct FlexibleGridView: View {
    
    let cols = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
    let colors: [Color] = [.yellow, .red, .purple, .green, .black, .blue, .orange, .pink, .gray]
    
    var body: some View {
        VStack {
            LazyVGrid(columns: cols, spacing: 10) {
                    ForEach(0...8, id: \.self) { i in
                        GeometryReader { proxy in
                        colors[i]
                            .overlay(
                                Text("Hi \(i)")
                            )
                            .frame(height: proxy.size.width)

                    }
                }
            }
            .frame(height: 300)
        }
        .padding()
    }
}

struct AdaptiveGridView_Previews: PreviewProvider {
    static var previews: some View {
        FlexibleGridView()
    }
}

The above code almost works but doesn't layout properly, see image below:

Resulting layout

Norman
  • 3,020
  • 22
  • 21
  • 1
    Does this answer your question https://stackoverflow.com/a/63027052/12299030? – Asperi Jan 19 '21 at 18:44
  • @Asperi Thank you for your help, the answer you referred to is precisely what I'm trying to accomplish. It also revealed that the problem with my code is due to the GeometryReader. Is it better to delete this question or mark it as a DUP? – Norman Jan 19 '21 at 19:00

0 Answers0