How can a View
adjust its ideal size in one dimension when the other dimension is clamped?
For instance, Text
exhibits this behavior. If constrained via .fixedSize
and given too little space in one dimension, then the ideal size for the other dimension will grow in response, if possible.
Using .fixedSize(horizontal: false, vertical: false)
Using .fixedSize(horizontal: false, vertical: true)
Using .fixedSize(horizontal: true, vertical: false)
It looks like Text
has somehow defined its ideal size as something like .frame(idealWidth: 400, idealHeight: 20)
in the first two cases. However, the part that's confusing me is that it seems to be modifying that in the third case to something like .frame(idealWidth: 80, idealHeight: 100)
.
How can we, like Text
, allow our View
to update its ideal size in response to a dimension(s) being clamped?
Here's a bit of code that shows this behavior in Text
which I described above:
VStack(spacing: 100) {
Group {
Text("ooooooooooooooooooooooooooooooooooo")
.fixedSize(horizontal: false, vertical: false)
Text("ooooooooooooooooooooooooooooooooooo")
.fixedSize(horizontal: true, vertical: false)
Text("ooooooooooooooooooooooooooooooooooo")
.fixedSize(horizontal: false, vertical: true)
}
.background(Color.green)
.frame(width: 75, height: 75)
.background(Color.blue)
}
With this font and repeating "o" content, Text
wants to basically have square space equal to about 7,000 points (338x20 ideal size for case #2 and 68x108 for case #3).
How could this be replicated in a custom View
? The minHeight
and minWidth
are not static; They depend on the parent having clamped a dimension or not. How can we, as the child, know which dimensions we've been clamped in, if any? The proposed size from the parent is still 75x75 in each example, so what is it that the child view has access to with which to base its ideal size off of? How is Text
doing this?
To make an answer more concrete, consider how you could replace the Text("oooooo")
instances with instances of a custom class which behaves similarly with regard to .fixedSize
. ie. attempt to maintain a 7,000 point square area, with a minimum 20 point height, preferring to grow horizontally first.