NavigationStack iOS16 with Route, how to pop back to root?
Asked Answered
L

1

0

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?

Longwise answered 22/4, 2023 at 11:59 Comment(1)
Does this work: path.removeLast(path.count) ?Ingenuity
P
3

Just clear the path

path = NavigationPath()

You can also make an extension

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

And then use

path.popToRoot()
Preceptive answered 22/4, 2023 at 15:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.