SwiftUI: Pop to root view when selected tab is tapped again

后端 未结 3 944
轮回少年
轮回少年 2020-12-03 16:08

Starting point is a NavigationView within a TabView. I\'m struggling with finding a SwiftUI solution to pop to the root view within the navigation stack when the selected ta

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 16:59

    Here is possible approach. For TabView it gives the same behaviour as tapping to the another tab and back, so gives persistent look & feel.

    Tested & works with Xcode 11.2 / iOS 13.2

    demo

    Full module code:

    import SwiftUI
    
    struct TestPopToRootInTab: View {
        @State private var selection = 0
        @State private var resetNavigationID = UUID()
    
        var body: some View {
    
            let selectable = Binding(        // << proxy binding to catch tab tap
                get: { self.selection },
                set: { self.selection = $0
    
                    // set new ID to recreate NavigationView, so put it
                    // in root state, same as is on change tab and back
                    self.resetNavigationID = UUID()
            })
    
            return TabView(selection: selectable) {
                self.tab1()
                    .tabItem {
                        Image(systemName: "1.circle")
                    }.tag(0)
                self.tab2()
                    .tabItem {
                        Image(systemName: "2.circle")
                    }.tag(1)
            }
        }
    
        private func tab1() -> some View {
            NavigationView {
                NavigationLink(destination: TabChildView()) {
                    Text("Tab1 - Initial")
                }
            }.id(self.resetNavigationID) // << making id modifiable
        }
    
        private func tab2() -> some View {
            Text("Tab2")
        }
    }
    
    struct TabChildView: View {
        var number = 1
        var body: some View {
            NavigationLink("Child \(number)",
                destination: TabChildView(number: number + 1))
        }
    }
    
    struct TestPopToRootInTab_Previews: PreviewProvider {
        static var previews: some View {
            TestPopToRootInTab()
        }
    }
    

提交回复
热议问题