Can someone help me understand the behavior of 'NavigationStack.count'. I don't understand how/when it's updated. In this example, I use the count to disable back navigation. But as you can see, initially(as expected), the back button is disabled on screen 1. But when I navigate to screen 2, and then back to screen 1, the back button flashes for less than a second even though the print statement shows that count is 1 and should disable back navigation.
import SwiftUI
struct ExploreDelayedNavigationPathCount: View {
@State private var navigationPath = NavigationPathWrapper()
init() {
navigationPath.path.append(0)
}
var body: some View {
NavigationStack(path: $navigationPath.path) {
Text("View to register navigationDestination only")
.navigationDestination(for: Int.self) { number in
SubView(number: number, navigationPath: navigationPath)
}
.navigationTitle("Hidden Root")
}
}
}
struct SubView: View {
let number: Int
var navigationPath: NavigationPathWrapper
var body: some View {
Text("Go to screen \(number + 1)")
.onTapGesture {
navigationPath.append(number + 1)
}
.navigationTitle("Screen \(number)")
.navigationBarBackButtonHidden(navigationPath.disableBackNavigation)
}
}
#Preview {
ExploreDelayedNavigationPathCount()
}
@Observable
class NavigationPathWrapper {
var path = NavigationPath()
var disableBackNavigation: Bool {
print("path.count \(path.count)")
return path.count == 1
}
func append(_ value: any Hashable) {
path.append(value)
}
}
UINavigationController. You probably need to control the back button from the UIKit side yourself if you want to avoid this.