1

HStack and Vstack usually base their layout on the maximum size of the subviews. Here is an example:

HStack {
    Color.orange
        .frame(idealWidth: 200, maxWidth: .infinity)
    Color.purple
        .frame(idealWidth: 100, maxWidth: .infinity)
}
.padding()
.frame(height: 100)

MaxWidth

However, when the same HStack is nested inside a ScrollView, the ideal size is used instead:

ScrollView(.horizontal) {
    HStack {
        Color.orange
            .frame(idealWidth: 200, maxWidth: .infinity)
        Color.purple
            .frame(idealWidth: 100, maxWidth: .infinity)
    }
}
.padding()
.frame(height: 100)

IdealWidth

So I'm wondering, is there a way to have an HStack or VStack base their layout on the ideal size, instead of the max size, without nesting inside a ScrollView?

One solution might be, if the subviews could be wrapped in some way so that they return their ideal size as the max size. Any suggestions on how to do this?

Of course, a custom Layout could be built to do the job. But can it be done without going this route?

1 Answer 1

2

Try

.fixedSize()

Fixes this view at its ideal size.

https://developer.apple.com/documentation/swiftui/view/fixedsize()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.