< How to control spacing around individual views using padding | How to place content outside the safe area > |
Updated for Xcode 14.2
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)
.foregroundColor(.black)
.frame(width: geometry.size.width * 0.33)
.background(.yellow)
Text("Right")
.font(.largeTitle)
.foregroundColor(.black)
.frame(width: geometry.size.width * 0.67)
.background(.orange)
}
}
.frame(height: 50)
Download this as an Xcode project
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.
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.