Hello.
I use NavigationStack for navigating in app. I have 4 screens - A, B, C, D. In some moment I have path [A, B, C] for NavigationStack. After user did action I should show path [A, B, D]. In other hands I should replace screen C with screen D.
struct HomeView: View {
@ObservedObject var viewModel: HomeViewModel
var body: some View {
NavigationStack(path: $viewModel.path) {
ContentView()
.navigationDestination(for: HomeViewModel.Path.self) { destination in
// B, C, D views here...
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
Solution looks like same as for UIKit. I replaced last item in stack. It works, but "push" animation broke.
var updatedPath = self.path
updatedPath.removeLast()
updatedPath.append(newPathItem)
self.path = updatedPath
I found suggest in Internet that you can remove view from stack after some delay. But it has some magic. For example 1 second delay works properly on iOS 18, but cause crash on iOS 16. 1 millisecond delay works on iOS 16, but sometimes didn't.
self.path.append(newPathItem)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1000)) {
UIView.setAnimationsEnabled(false)
self.path.remove(at: self.path.count - 2)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1)) {
UIView.setAnimationsEnabled(true)
}
}
It is easy task to replace current top screen in UINavigationController of UIKit. How I can do it properly in SwiftUI and save animation?