Home > Software design >  Set the width of an Image to half the width of its HStack container view in SwiftUI?
Set the width of an Image to half the width of its HStack container view in SwiftUI?

Time:12-23

So I just want to do something pretty simple which is have an Image take half the size of its container and a Vstack the other half.

Im currently doing this to force both views to take as much space as they can with maxWidth: .infinity, so they end up taking equal amounts of space:

    struct ContentView: View {
    var body: some View {
        HStack {
            Image("landscape")
                .resizable()
                .scaledToFill()
                .frame(maxWidth: .infinity, maxHeight: 170)
            VStack {
                Text("Test")
                Text("Test 2")
            }
            .frame(maxWidth: .infinity)
        }
        .frame(maxWidth: .infinity, maxHeight: 170)
        .background(Color.red)
        .padding()
    }
}

But it ends up in this poor result, sadly:

enter image description here

Any tips? I saw GeometryReader might come in handy here but seems to push my Views all the way to the top and end up with unwanted results.

CodePudding user response:

you need to add a fixedSize() modifier to HStack and keep it's vertical to true.

var body: some View {
    HStack {
        Image("1")
            .resizable()
            .scaledToFill()
            .frame(maxWidth: .infinity, maxHeight: 170)
        
        VStack {
            Text("Test")
            Text("Test 2")
        }
        .frame(maxWidth: .infinity)
    }
    .frame(maxWidth: .infinity, maxHeight: 170)
    .background(Color.red)
    .padding()
    .fixedSize(horizontal: false, vertical: true)
}

you can read more about enter image description here

  • Related