What is the best practice to achieve popToRootViewController like functionality in SwiftUI? There are couple of ways to do it and one of them is described nicely here (https://stackoverflow.com/questions/57334455/swiftui-how-to-pop-to-root-view) via publish event but it losses the animation while popping to root. Please suggest.
popToRootViewController in SwiftUI
With iOS 16, you can now use NavigationStack. You can use the NavigationPath variable in NavigationStack
in order to take control over the stack of views you have pushed and popped.
NavigationPath
allows you to create a type-erasing variable to keep track of your views, but it is easy to create one with any type, like below, where I use an array of Strings.
struct ContentView : View {
@State private var path: [String]
var body: some View {
NavigationStack(path: $path){
List{
NavigationLink("title", value: "nextView")
}
.navigationDestination(for: String.self){ str in
DetailView(strToShow: str)
}
}
}
}
Each NavigationLink will pass a value to the .navigationDestination modifier and will add the view to the path variable. Then, at any point in time, you can call path.popLast()
to go backwards by one view, or set the path back to an empty array like this: path = []
. This will pop you to the first page. This can be called in a matter of ways, for instance you can add a button to the toolbar that does this.