I've got a VStack
with 3 Text
s in it. Each has a different length string. I'd like the VStack
's width to be just big enough to fit the widest Text
, but I'd also like all three Text
s to fill the VStack horizontally.
By default, with this code:
VStack(spacing: 4.0) {
ForEach(1..<4) {
Text(Array<String>(repeating: "word", count: $0).joined(separator: " "))
.background(Color.gray)
}
}
I get:
I want:
In UIKit, I could do this with a vertical UIStackView
whose alignment
property was set to .fill
. VStack
doesn't have a .fill
alignment. The suggested solution I've seen is to modify the frame of each child of the stack view (ie. each Text
) with .infinity
for maxWidth
.
The suggestion I've found is to modify the Text
s with .frame(maxWidth: .infinity)
. However, this makes the whole VStack
expand to (presumably) its maximum size:
Is there a way to make the VStack
naturally grow to the size of its widest child, and no larger, while making all its children the same width?