I have a HStack with Spacers and a Text.
HStack {
Spacer()
Text("Some Text")
Spacer()
}
Now I want the first Spacer to take X% of the available space (excluding the space taken by Text
) and the bottom to take the rest.
If I use Geometry Reader, and do something like below to the first Spacer –
Spacer()
.frame(width: geometry.size.width * (X/100))
It doesn’t take into account the space occupied by the Text
.
Is there any way to divide the "available" space between spacers?
2
Answers
What you are looking for are
PreferenceKeys
. Essentially, they keep track of the sizes of certain views, and then you can use those sizes to compute what you need. They are most commonly used to keep multiple views the same size, even though they would otherwise have different sizes. I am giving you a long and short solution on this:Long solution:
The Short Solution thanks to FiveStarBlog and @ramzesenok on Twitter:
And use the extension:
They do the same thing, but the extension handles it very neatly without the extra code in your view. I posted it so that you could see how
PreferenceKeys
work.Here is a decent solution that requires just one
GeometryReader
.For more information, check this article.