I can't wrap my head around how to make two buttons the same width, without resorting to ugly hacks like GeometryReader. What is otherwise easy to implement using UIStackView or AutoLayout, becomes a nightmare in SwiftUI.
I tried the following, plus some other variations, but nothing works. What is the "official way" to make two vertically aligned buttons of the same width?
1)
VStack(alignment: .leading) {
Button("Short", action: {})
.frame(maxWidth: .infinity)
Button("Long title", action: {})
.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
2)
VStack(alignment: .leading) {
Button(action: {}) {
Text("Short")
.frame(maxWidth: .infinity)
}
Button(action: {}) {
Text("Long title")
.frame(maxWidth: .infinity)
}
}
.frame(maxWidth: .infinity)
3)
VStack(alignment: .leading) {
Button(action: {}) {
Text("Short")
}.frame(maxWidth: .infinity)
Button(action: {}) {
Text("Long title")
}.frame(maxWidth: .infinity)
}
.frame(maxWidth: .infinity)
To make a Button flexible, you can give its label an infinite width.
VStack {
Button(action: {}) {
Text("Short")
.frame(maxWidth: .infinity)
}
Button(action: {}) {
Text("Long title")
.frame(maxWidth: .infinity)
}
}
Or...
VStack {
Button(action: {}) {
Spacer()
Text("Short")
Spacer()
}
Button(action: {}) {
Spacer()
Text("Long title")
Spacer()
}
}
To get an appearance similar to @darkpaw's example, you can apply the .buttonStyle(.borderedProminent)
modifier to the VStack
or each individual Button
, and use the tint
modifier to customize the colors.