ios – How Pop to root view using TabView in SwiftUI


Replace the ContentView body with TabView. Then handle onTapGesture(count: 2)

enum Tab {
    case list
    case detail
}

struct ContentView: View {
    @State private var selection: Tab = .detail
    @State private var path = NavigationPath()

    var body: some View {
        TabView(selection: $selection) {
            DetailView(path: $path, number: 0)
                .tabItem {
                    Label("Detail", systemImage: "star")
                }
                .tag(Tab.detail)

            //Config other tabItem if needed
            //...
        }
        .onTapGesture(count: 2) {
            guard selection == .detail else { return }
            path = NavigationPath()
        }
    }
}

Now DetailView is a root view of Tab = .list. So if you want to push to another view, do it on navigationDestionation here

struct DetailView: View {
    @Binding var path: NavigationPath
    var number: Int
    var body: some View {
        NavigationStack {
            VStack {
                Button {
                    path.append(1)
                } label: {
                    Text("Go to Random Number")
                }
            }
            .navigationTitle("Number: \(number)")
            .navigationDestination(for: Int.self) { num in 
                //Put random number's view here
            }
        }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img