0

I would like to manage all my Views on the NavigationPath with an object NavigationObj, so I can easily manage my headers on the NavigationPath. I can't figure out how to send a View into NavigationObj and keep NavigationObj Hashable so it can be added onto the NavigationPath. Here is an example with the code to set the View on NavigationObj commented out.

@available(iOS 16.0, *)
final class GlobalClass1: ObservableObject {
    @Published public var navigationPath = NavigationPath()
}

@available(iOS 16.0, *)
struct NavigationObj: Identifiable, Hashable {
    let id = UUID()
    let name: String
    var destination: some View{ContentView111()}
    
    var body: some View {
        //add custom headers and controls depending on destination
        destination
    }
    
    var isEmpty: Bool {
        name.isEmpty
    }
}

@available(iOS 16.0, *)
struct ContentView111: View {
    @EnvironmentObject private var globalObj: GlobalClass1
    var body: some View {
        NavigationStack(path: $globalObj.navigationPath) {
            VStack{
                // Button to navigate deeper
                Button(action: {
                    // Is it possible to pass a View to NavigationObj to navigate to like the commented out part?
                    globalObj.navigationPath.append(NavigationObj(name: "New"))//{ ContentView111() })
                }, label: {
                    Text("go deeper")
                })
                if globalObj.navigationPath.count > 0{
                    // Button to pop to root
                    Button(action: {
                        globalObj.navigationPath = NavigationPath()
                    }, label: {
                        Text("pop to root")
                    })
                }
            }
            .navigationDestination(for: NavigationObj.self) { item in
                item.destination
            }
        }
    }
}
micah
  • 838
  • 7
  • 21
  • You trying to erase the core of SwiftUI, SwiftUI is all about identity if you start overriding how this is determined by using Identifiable and Hashable in a View you will find endless issues – lorem ipsum Jan 23 '23 at 16:26
  • @loremipsum Thanks for the input. If the Views cannot be abstracted from the NavigationPath, would the only way to manage headers on the NavigationPath be to create `.navigationDestination(for: AObj.self) { item in` . . . for every possible navigation? – micah Jan 23 '23 at 16:45
  • You can reuse with `ViewModifier`s but yes the general idea is that all possible `View`s come from `navigationDestination` there are a few exceptions like with `Binding`. – lorem ipsum Jan 23 '23 at 20:12
  • @loremipsum Thanks! I found how to abstract the Views out here https://stackoverflow.com/questions/73723771/navigationstack-not-affected-by-environmentobject-changes – micah Jan 23 '23 at 20:43

0 Answers0