Search code examples
swiftuiswiftui-navigationlinkswiftui-navigationviewswiftui-navigationstack

NavigationStack iOS16 with Route, how to pop back to root?


I have the following navigation stack using route to go to differnet views:

import SwiftUI
import FirebaseAuth
import WebKit
enum Route:String, Hashable {
    case linkSettings,
         linkWallet
}
struct Dashboard: View {
    @State private var path = NavigationPath()
    @State private var offsetX: CGFloat = 0
    @State private var maxOffsetX: CGFloat = -1
    @AppStorage("uid") var userID: String = ""
    let featured = Featured.featuredList
    var body: some View {
        NavigationStack(path: $path) {
            GeometryReader {
                reader in
                ZStack {
                    Color("db").ignoresSafeArea()
                    VStack {
                        Header()
                        Spacer()
                        FeaturedCarousel(
                            reader: reader,
                            featured: featured,
                            offsetX: $offsetX,
                            maxOffsetX: $maxOffsetX)
                        Spacer()
                        Footer()
                    }
                    .navigationDestination(for: Route.self) {
                        route in
                        switch route {
                        case.linkSettings:Settings(path: $path)
                        case.linkWallet:Wallet(path: $path)
                        }
                    }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
        .onAppear {}
    }
}

In the other views, I simply bind the path with:

@Binding var path: NavigationPath

But if I use:

Button {path.removeLast()}label: {Text("Back to root!")}

It just goes back to the previous view, not the root.

How to go back to root?


Solution

  • Just clear the path

    path = NavigationPath()
    

    You can also make an extension

    extension NavigationPath{
        func popToRoot() {
            self = NavigationPath()
        }
    }
    

    And then use

    path.popToRoot()