Items inside a SwiftUI LazyVGrid
shrink to their minWidth
(80 points in my example below) when the grid view expands enough to fit another column. This is visually expected when there are multiple rows:
However, when there's only one row, this is visually clumsy (in my opinion):
Instead, when there's only one row, I would like the items to expand all the way up to their maxWidth
and then stay there:
I achieved the last result by hardcoding a maxWidth
on the LazyVGrid
but:
- I'm not sure how to programmatically calculate what the grid's
maxWidth
would need to be and - the items never reach their
maxWidth
(in my example that would be 150 points) because the current behaviour shrinks them repeatedly as the available space grows.
You can see this exact problem in the swiftUI macOS Shortcuts app.
The better, desired behaviour can be seen in:
- Books (Library > All)
- Notes ("Gallery" view)
- Music
- Photos etc
The pertinent parts of my code:
let items = ... /// My items here
let gridItems = [
GridItem(.adaptive(minimum: 80))
]
var body: some View {
VStack(alignment: .leading) {
Text("LazyVGrid:")
HStack {
LazyVGrid(columns: gridItems) {
ForEach(items, id: \.self) { item in
itemView
}
}
.frame(maxWidth: 510) /// For the final sample above
Spacer()
}
Spacer()
}
}
private var itemView: some View {
GeometryReader { geo in
HStack {
VStack {
Text("\(Int(geo.size.width))")
}
}
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 50)
}