I have an HStack
with three Texts
:
HStack {
Text("Hey")
Text(".")
Text("What's up?")
}
All I want is the HStack
to fill the available space of its parent container under the constraint that all three Texts
have the same font size in the end.
The following naive approach obviously doesn't work:
struct ThreeTextsView: View {
var body: some View {
HStack {
Text("Hey")
Text(".")
Text("What's up?")
}
.font(.system(size: 500)) // set a crazy-height font-size
.minimumScaleFactor(0.01) // so it can be scaled down
.frame(width: 200, height: 200) // ← this only simulates the size of the container
}
}
This is the output:
Each Text
view is scaled individually according to the preferences applied to the whole HStack
, so we end up with three different font sizes in the same HStack
. Of course, I could use a fixed font size instead, but then the compound of the three texts would not dynamically fill its container when the container is resized.
How can I solve this (without magic numbers and additional assumptions)?
The three Texts
must be baseline-aligned in the end. (That's clearly not the case in the example above.)
Note: John Sundell has written a great article on how to give views an equal width or height based on their intrinsic (ideal) sizes. However, my problem is a little different as it also requires knowledge of the outside world (the container's size), so it has one additional constraint.