How to provide relative sizes using GeometryReader
How to provide relative sizes using GeometryReader êŽë š
Updated for Xcode 15
Although it's usually best to let SwiftUI perform automatic layout using stacks, it's also possible to give our views sizes relative to their containers using GeometryReader
. For example, if you wanted two views to take up half the available width on the screen, this wouldn't be possible using hard-coded values because we don't know ahead of time what the screen width will be.
To solve this, GeometryReader
provides us with an input value telling us the width and height we have available, and we can then use that with whatever calculations we need. So, if we had two views and we wanted one to take up a third of the screen and the other take up two thirds, we could write this:
GeometryReader { geometry in
HStack(spacing: 0) {
Text("Left")
.font(.largeTitle)
.foregroundStyle(.black)
.frame(width: geometry.size.width * 0.33)
.background(.yellow)
Text("Right")
.font(.largeTitle)
.foregroundStyle(.black)
.frame(width: geometry.size.width * 0.67)
.background(.orange)
}
}
.frame(height: 50)
Note
GeometryReader
doesn't take into account any offsets or spacing further down in the view hierarchy, which is why there is no spacing on the HStack
â if we allowed spacing in there, the views would be a little too large for the available space.