Home > Mobile >  Unwind NavigationView to root when switching tabs in SwiftUI
Unwind NavigationView to root when switching tabs in SwiftUI

Time:01-02

I have an app with a few tabs, and on one of those there is a NavigationLink which nests a couple of times.

I want to be able to switch tabs, and when going back to the other tab to have unwound all links to the root view.

I have seen these: enter image description here

CodePudding user response:

You'll need to keep track of the tab selection in the parent view and then pass that into the child views so that they can watch for changes. Upon seeing a change in the selection, the child view can then reset a @State variable that change the isActive property of the NavigationLink.

class NavigationManager : ObservableObject {
    @Published var activeTab = 0
}

struct MyTabView: View {
    @StateObject private var navigationManager = NavigationManager()
    
    var body: some View {
        TabView(selection: $navigationManager.activeTab) {
            TabOne().tabItem { Image(systemName: "1.square") }.tag(0)
            TabTwo().tabItem { Image(systemName: "2.square") }.tag(1)
        }.environmentObject(navigationManager)
    }
}

struct TabOne: View {
    var body: some View {
        Text("1")
    }
}

struct TabTwo: View {
    @EnvironmentObject private var navigationManager : NavigationManager
    @State private var linkActive = false
    
    var body: some View {
        NavigationView {
            NavigationLink("Go to sub view", isActive: $linkActive) {
                TabTwoSub()
            }
        }.onChange(of: navigationManager.activeTab) { newValue in
            linkActive = false
        }
    }
}

struct TabTwoSub: View {
    var body: some View {
        Text("Tapping \(Image(systemName: "1.square")) doesnt unwind this view back to the root of the NavigationView")
            .multilineTextAlignment(.center)
    }
}

Note: this will result in a "Unbalanced calls to begin/end appearance transitions" message in the console -- in my experience, this is not an error and not something we have to worry about

  • Related