I have a GeometryReader nested inside of a NavigationView. Inside the GeometryReader I am using the dimensions supplied by the GeometryProxy with an if-statement. In my project I stumbled over the fact, that the content inside the GeometryReader is evaluated twice and the provided dimensions are width 0 and height 0 the first time. Also the onAppear() method of the content inside of the if case is called twice which lead to more problems.
Could someone explain that behavior so I can improve my code?
I made a minimal example to showcase the problem:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView() {
NavigationLink(destination: SecondView()) {
Text("Click me!")
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct SecondView: View {
private func showHorizontal(_ w: CGFloat, _ h: CGFloat) -> Bool {
print("Dimensions \(w), \(h)")
return (w > h)
}
var body: some View {
GeometryReader { proxy in
if self.showHorizontal(proxy.size.width, proxy.size.height) {
Text("Landscape")
.onAppear() {
print("Landscape appeared")
}
} else {
Text("Portrait")
.onAppear() {
print("Portrait appeared")
}
}
}
.onAppear() {
print("GeometryReader appeared")
}
}
}
On my iPad in landscape orientation I get the following console output:
Dimensions 0.0, 0.0
Dimensions 1194.0, 688.0
GeometryReader appeared
Landscape appeared
Landscape appeared