When developing SwiftUI applications, most of the time, we don't have to worry about the exact location or size of an item on the screen. However, there are cases where we need to ensure that certain items have specific sizes or locations on the app. This is where the Geometry Reader comes in.
Geometry Reader is a useful tool for any SwiftUI developer as it allows us to get the exact size and location of objects on the screen. Additionally, the GeometryReader is adaptive when the device rotates. It is the perfect helper if we want to resize our view when a user switches from portrait to landscape mode (or vice-versa).
Let's take a look at a basic example of how to use the Geometry Reader. We'll start with an HStack containing two rectangles, one coloured red and the other blue. By default, SwiftUI automatically resizes our objects to be the same size, but what if we want one rectangle to be two-thirds of the screen while the other is one-third?
Here's a code example:
HStack {
Rectangle()
.fill(Color.red)
.frame(width: UIScreen.main.bounds.width * 0.66)
Rectangle()
.fill(Color.blue)
.frame(width: UIScreen.main.bounds.width * 0.33)
}
However, we'll quickly run into issues with this approach when we rotate the device. The width of the red rectangle is still two-thirds of the width of the device, even though it's not taking into account the device's new height. This is where Geometry Reader can help us.
Using Geometry Reader, we can dynamically calculate the size and location of the rectangles based on the current screen's dimensions, ensuring that they are always the correct size and in the correct location. Here's how we can update our previous example to use Geometry Reader:
HStack {
GeometryReader { geo in
Rectangle()
.fill(Color.red)
.frame(width: geo.size.width * 0.66)
}
GeometryReader { geo in
Rectangle()
.fill(Color.blue)
.frame(width: geo.size.width * 0.33)
}
}
In this updated example, we're using two Geometry Readers to calculate the size of the rectangles dynamically. By passing in the geo
parameter, we can access the size of the Geometry Reader and use it to calculate the width of each rectangle.
While the Geometry Reader can be a powerful tool for SwiftUI developers, it's essential to keep in mind that it can be expensive and slow down the UI when overused. It's best to try and build screens without using a Geometry Reader if possible, but if we do need to use one, make sure to use it sparingly.
In conclusion, the Geometry Reader is an incredibly useful tool for SwiftUI developers looking to add more dynamic animations and effects to their apps. With its ability to calculate the size and location of objects on the screen, we can make our apps more engaging and interactive, improving the user experience.