I am writing an anki-like app with language exercises. Completing an exercise leads you to the exercise with the next word, and so on, indefinitely. I want to transition between words using navigation. This is a simplified example of what I have come up with:
struct ContentView: View {
@State private var page: Int = 0
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
VStack {
NavigationLink("Go to page \(page)", value: page)
}
.navigationDestination(for: Int.self) { currentPage in
VStack {
Text("You selected \(currentPage)")
Button("Next page") {
page += 1
path.removeLast()
path.append(page)
}
}.onAppear() {
print("View with page \(page) is appearing")
}
}
}
}
}
I use NavigationPath with pushing and popping to "replace" the uppermost view with the next word exercise. Note that I don't want to just "push" the view into the stack, because then it will grow indefinitely. I also want the "back" button to lead to the main menu, not the previous exercise.
The code provided works, but there is no animation when transitioning to next page. Also, the "onAppear" method is not called when navigating to the next page.
Suspecting that it has to do with view hierarchy not changing, I've tried make id of the VStack view depend on the page using .id modifier, and also pushing different types of objects into path - none of these helped.
Would be really grateful for any ideas on how to fix this!