How to use navigation paths when views are the same across tabs?

199 Views Asked by At

I have a tab view at the highest level, and right now, only one view has a navigation path cause I am working on adding the others, but I've run into a blocker first. I was planning for each tab view to have its own path.

So my feedview can navigate to my profileview which can navigate to subviews under all of my tabs. Almost every view can exist under each tab view, potentially even multiple times. I want the app to be easy to get to whatever you need from wherever you need.

I have an enum to navigate through all of my subviews under feedviews path. And then in each view, I navigate using: NavigationLink(value: FeedNavigation.profile(user)). But if navigationlinks from my profile view contain FeedNavigation.profile(user) then how do I reuse that same navigationlink when the path it originated from is not FeedNavigation?

I tried to reduce the amount of code because I think the problem is a broader concept than it is fixing my actual code.

Example: Feed View -> Profile View -> Book View (FeedNavigation path)

Example 2: Profile View -> Book View -> Potentially back to Feed View (would want to create a ProfileNavigation path)

Both profile views have the same navigation link to access the next view. so if I tie profileviews link to a specific path, that path won't always be how I got there.

class NavigationManager: ObservableObject {
    @Published var feedPath = [FeedNavigation]()

enum FeedNavigation: Hashable, Codable {
    case profile(User)
    case notification
    case chat
}

}
TabView(selection: $currentTab) {
    
    NavigationStack(path: $navigationManager.feedPath) {
        FeedView()
    }
    .tag(Tabs.feed)
    
    NavigationStack() {
        SearchView()
    }
    .tag(Tabs.search)
    
    NavigationStack() {
        ProfileView(user: user)
    }
    .tag(Tabs.profile)
    
}
struct FeedView: View {
    @EnvironmentObject var navigationManager: NavigationManager
    var body: some View {
        NavigationLink(value: FeedNavigation.profile(user)) {
            Text("Click to see user's profile")
        }
        .navigationDestination(for: FeedNavigation.self) { state in
            switch state {
            case .profile(let user):
                ProfileView(user: user)
            case .notification:
                NotificationsView()
            case .chat:
                ConversationsView()

        }
    }
}
struct ProfileView: View {
   var body: some View {
         NavigationLink(value: FeedNavigation.notifications)) {
           Text("Go to notifications")
       }
   }
}

In this example code, now all my profile links have the FeedNavigation path, even though the profile view would need its own path as it is its own tab view.

0

There are 0 best solutions below