The new Grid View looks like it brings us a simple way to get row-column layouts into our SwiftUI apps!
I wonder if someone can help me with one aspect: I have a situation similar to the one described for the Pet Leaderboard App in the "Compose custom layouts with SwiftUI" video. But I want to save space by putting the Cat/Goldfish/Dog voting buttons in the leaderboard table itself, in the first column, instead of the labels. Here's the code for a simplified version of that table:
import SwiftUI
struct TableDemo: View {
var body: some View {
Grid(alignment: .leading) {
GridRow {
Button {
// vote for Cat
} label: {
Text("Cat").fontWeight(.bold).foregroundColor(.white).padding().background(.green).cornerRadius(8)
}
Text("23").fontWeight(.bold).foregroundColor(.white).gridColumnAlignment(.trailing)
}
GridRow {
Button {
// vote for Goldfish
} label: {
Text("Goldfish").fontWeight(.bold).foregroundColor(.white).padding().background(.green).cornerRadius(8)
}
Text("3").fontWeight(.bold).foregroundColor(.white)
}
}
.padding(20)
.background(Color(red: 50.0/255, green: 85.0/255, blue: 125.0/255))
.cornerRadius(16)
}
}
struct TableDemo_Previews: PreviewProvider {
static var previews: some View {
TableDemo()
}
}
which looks like this:
That result is visually unappealing because the buttons are inconsistent. It's nice that the Grid column is as wide as the widest button - that part is a big win from using the Grid View! But I'd like to get them to conform to the width of the widest button.
The normal solution for some situations is to set an infinite maxWidth to the buttons. eg:
Text("Cat").fontWeight(.bold).frame(maxWidth: .infinity).foregroundColor(.white).padding().background(.green).cornerRadius(8)
But that results in the entire column expanding to take all available space:
So what can we do, other than resorting to a PreferenceKey based approach, to solve this? Is there an official Grid-centric way of fixing this?
This is the desired layout (I manually sized the buttons):