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: