If I initiate the NavigationStack with a path and traverse upwards with the back button, onAppear doesn’t trigger for the views I’m traversing. However, if I manually traverse the same path downwards, navigating back is triggered on every view as expected. I want to track the value for the screen presented outside the NavigationStack. Explanations and alternative tracking solutions are welcome.
Here are my actions and output:
Starting the application with an initial navigation path:
onAppear view: 0
onAppear view: 1
onAppear view: 2
Navigating up to view 0:
(Expected output:
onAppear view: 1
onAppear view: 0)
Output:
…nothing
Navigating down manually:
onAppear view: 1
onAppear view: 2
Navigating up to view 0:
(Now I get the expected output)
onAppear view: 1
onAppear view: 0
import SwiftUI
struct SwiftUIView: View {
@State private var navigationPath: NavigationPath
init() {
var startPath = NavigationPath()
startPath.append(1)
startPath.append(2)
self._navigationPath = State(initialValue: startPath)
}
var body: some View {
NavigationStack(path: $navigationPath) {
Text("View 0")
.navigationDestination(for: Int.self) { number in
MyDestinationView(number: number)
}
.onAppear {
print("onAppear view: 0")
}
NavigationLink("Next", value: 1)
}
}
}
struct MyDestinationView: View {
let number: Int
var body: some View {
Text("I'm view: (number)")
.onAppear {
print("onAppear view: (number)")
}
NavigationLink("Next", value: number + 1)
}
}
#Preview {
SwiftUIView()
}
4