Home > front end >  Where to place global NavigationPath in SwiftUI
Where to place global NavigationPath in SwiftUI

Time:12-17

I'm currently developing an app using NavigationStack. I wonder where should I put the NavigationPath variable so I can modify it anywhere.

I tried to put it inside the root view as a State variable, but it seems difficult for me to modify it inside deeply-nested views.

struct RootView: View {
    @State var path = NavigationPath()
    
    var body: some View {
        NavigationStack(path: $path) {
            // ...
        }
    }
}

struct SubView: View {
    var body: some View {
        Button("Push to root") {
            // how should I access `path` from here?
        }
    }
}

I also tried to put it as a global variable, but this may result that navigation are shared among all scene, which is not what I intended.

class Router: ObservableObject {
    static var shared = Router()
    @Published var path = NavigationPath()
}

struct RootView: View {
    @ObservedObject var router = Router.shared
    
    var body: some View {
        NavigationStack(path: $router.path) {
            // ...
        }
    }
}

struct SubView: View {
    @ObservedObject var router = Router.shared
    
    var body: some View {
        Button("Push to root") {
            router.path = []
        }
    }
}

I would appreciate if someone were to provide a workable design or any suggestions.

CodePudding user response:

Use @Binding the same as you would to pass down write access to any other kind of @State. Try not to revert to objects to solve problems, that'll lead to bugs.

  • Related