I would like to create a grid with 24 Items in 4 rows, so each row should have 6 items. All items should be equally sized but fill the whole space available, no matter what device the grid is rendered on.
I already achieved a flexible height for the rows, but the GridItems do not push out in horizontal dimension, although it is a shape, that is said to be pushing out. Well within a LazyHGrid it seems not to push out.
This is my code:
struct AllAchievementsView: View {
var gridRows: Array<GridItem> { [GridItem(), GridItem(), GridItem(), GridItem()] }
var body: some View {
ZStack {
Color.black
LazyHGrid(rows: gridRows) {
ForEach(0..<24) { index in
RoundedRectangle(cornerRadius: 10).foregroundColor(.blue)
}
}.padding()
}
}
}
I tried all variants on GridItem sizing, I tried to add a frame on my Rectangle with .infity, etc. couldn't realize it. Do I really have to make the math programmatically with a GeometryReader?
I add two images: One shows the result of this code, the other shows, what I want to realize.
The GridItem
is filled/aligned according to the size of content, but the Rectangle
has no own size, so you see used some minimum default values.
Here is a possible solution (tested with Xcode 12 / iOS 14)
struct AllAchievementsView: View {
let sp = CGFloat(5)
var gridRows: Array<GridItem> { Array(repeating: GridItem(spacing: sp), count: 4) }
var body: some View {
GeometryReader { gp in
ZStack {
Color.black
LazyHGrid(rows: gridRows, spacing: sp) {
ForEach(0..<24) { index in
RoundedRectangle(cornerRadius: 10).foregroundColor(.blue)
.frame(width: gp.size.width / 6 - 2*sp)
}
}
.padding()
}
}
}
}