3

I've got a VStack with 3 Texts 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 Texts 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:

VStack with three different width Texts

I want:

VStack with three same width Texts

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 Texts with .frame(maxWidth: .infinity). However, this makes the whole VStack expand to (presumably) its maximum size:

Wide VStack

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?

Andrew Madsen
  • 20,769
  • 5
  • 52
  • 92

1 Answers1

4

Just add .fixedSize().

struct ContentView: View {
    var body: some View {
    
        VStack(spacing: 4.0) {
            ForEach(1..<4) {
                Text(Array<String>(repeating: "word", count: $0).joined(separator: " "))
                    .frame(maxWidth: .infinity) /// keep the maxWidth
                    .background(Color.gray)
            }
        }
        .fixedSize() /// here!
    }
}

Result:

3 Texts with gray background stacked vertically, all 3 gray backgrounds have the largest Text's width

aheze
  • 6,076
  • 3
  • 6
  • 40