A similar question has been answered for Android Compose in this post. I was wondering if the same can be done for SwiftUI?
Example:
HStack {
VStack {
ContentWithUnknownHeight()
NextContentWithUnknownHeight()
}
.frame(width: geometry.size.width * 0.8)
Image("User")
.resizable()
.frame(width: geometry.size.width * 0.2)
}
.frame(minHeight: 100)
HStack’s height should not be fixed but grow if its childrens do. If VStack is taller than the Image, how can I fill the Image’s height to its parent’s without influencing its height?
What I have:
Expected Result:
2
Answers
An
HStack
automatically adopts the height of the tallest child.However, your question seems more concerned about the height of a child inside the
HStack
and your code example has an image in this position. Assuming you actually want to scale the image to fill (as opposed to scaling to fit, which is how the code is implemented), then one way is to show the image in an overlay over theHStack
:.frame
modifier that is setting a fixed height on theHStack
.Image
inside theHStack
with aSpacer
.HStack
will then be determined by the first child.alignment: .trailing
.If
SomeMoreContentWithUnknownHeight
is the only content left in theHStack
then you don’t even need to use anHStack
, you can apply the overlay directly to this content instead. Just use padding to reserve space for the overlay content:To make the
HStack
doesn’t grow taller than its tallest child needs, addto the
HStack
.Then, if the other views are views that naturally expand (e.g.
Divider
,Rectangle
,Image(...).resizable()
), they will expand to fill the height automatically. For an image, you might want it to bescaledToFill
, like in Benzy Neez’s answer.For views that do not naturally expand, like
Text
, you can make them do that by putting them as an overlay of some view that does naturally expand, plusmaxHeight: .infinity
.Some views like
Button
s may need special handling, to expand their tappable area, not just their frame. See also SwiftUI: Increase tap/drag area for user interaction