how can I know the height of the second rectangle? That second rectangle is the game board and I need to know the dimensions.
In the simplest form, the solution could be like this:
struct SomeScreen: View {
@State var boardHeight: CGFloat = 0 // <-- preserve the height
var body: some View {
VStack(spacing: 0) {
Rectangle()
.fill(.red)
.frame(height: 140) // <-- first rectangle takes fixed height
GeometryReader { geometry in
Rectangle() // <-- takes the remaining height
.fill(.green)
.onAppear {
boardHeight = geometry.size.height
}
}
Rectangle()
.fill(.blue)
.frame(height: 140) // <-- last rectangle takes fixed height
Text("\(boardHeight)")
}
.frame(maxWidth: .infinity, maxHeight: .infinity) // <-- takes the whole screen
}
}
So you define 2 rectangles with the fixed height, the one in the middle then takes "the remaining space". And we set VStack
that holds them to take the whole screen, so middle rectangle will occupy the remaining space of the screen. GeometryReader
will give you the height of that rectangle
But it also really depends what you are doing. Also consider not fixing the height to specific numbers: define constraints and let layout help you with dimensions. Maybe the space could be dictated by the content (with some maxHeight
defined), or maybe you could define it relatively to the size of the screen, e.g. 20% (using the same GeometryReader
).
Bonus question: how do take into the account the safe area in devices with notch and ignore it on devices without notch?
By default iOS would preserve the safe area, and I recommend letting iOS manage it for you even on the phones without the notch, especially for interactive content and text. You can, however place background (since it's not interactive) so that it takes the entire space, including the areas that are not safe.
In general this is done with the ignoresSafeArea
modifier:
VStack {
Rectangle()
...
}
.background(
Color.yellow.ignoresSafeArea()
)