How to use ideal size for HStack and VStack layout, instead of max size

79 views Asked by At

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

There are 1 answers

0
lorem ipsum On BEST ANSWER

Try

.fixedSize()

Fixes this view at its ideal size.

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