blub
blub

Reputation: 712

How to make subview fit all available vertical space in HStack?

I have two VStacks inside a HStack. Let's say the first has height 400px, and the second has height 300px. I'd like to set the background color of the two VStacks to be blue and red. But when I do so, because the second VStack doesn't use the full vertical space, the red ends up being a bit shorter. I want it to be the same height as the first.

I'm wondering if there is a general way to do this? I won't know the image dimensions / text in advance, so I can't just set the frame to be a fixed height.

Thanks so much!

HStack(alignment: .top) {
    VStack {
        Image1
        Text1
    }.background(Color.blue)
    VStack {
        Image2
        Text2
    }.background(Color.red)
}

enter image description here

Upvotes: 2

Views: 1502

Answers (2)

Asperi
Asperi

Reputation: 258541

Here is a solution.

Tested with Xcode 11.4 / iOS 13.4 with some replicated code

demo

HStack(alignment: .top) {
    VStack {
        Image1
        Text1
          .frame(maxHeight: .infinity, alignment: .top)  // << here !!
    }.background(Color.blue)
    VStack {
        Image2
        Text2
          .frame(maxHeight: .infinity, alignment: .top)  // << here !!
    }.background(Color.red)
}
.fixedSize(horizontal: false, vertical: true)    // << here !!

Upvotes: 2

Frankenstein
Frankenstein

Reputation: 16381

Add a Spacer:

VStack {
    Image2
    Text2
    Spacer()
}.background(Color.red)

Upvotes: 2

Related Questions