TabView resets navigation stack when switching tabs

前端 未结 3 1314
忘掉有多难
忘掉有多难 2020-11-29 20:24

I have a simple TabView:

TabView {
    NavigationView {
        VStack {
            NavigationLink(destination: T         


        
3条回答
  •  伪装坚强ぢ
    2020-11-29 21:20

    So, this does "preserve" the detail view when switching tabs, but only by visibly pushing the detail view when switching back to tab 1. I have been unsuccessful at disabling this with, for example, .animation().

    In addition, you pretty much have to override the navigation bar items in the DetailView, because the default back button behaves oddly (comment out the .navigationBarItems() line to see what I mean).

    With those caveats, this does qualify as a workaround.

    struct ContentView: View {
        @State var showingDetail = false
    
        var body: some View {
            TabView {
                NavView(showingDetail: $showingDetail)
                    .tabItem { Text("First") }
                    .tag(0)
                Text("Second View")
                    .tabItem { Text("Second") }
                    .tag(1)
            }
        }
    }
    
    struct NavView: View {
        @Binding var showingDetail: Bool
    
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink(destination: DetailView(showing: $showingDetail), isActive: $showingDetail) {
                        Text("Go to detail")
                    }
                }
            }
        }
    }
    
    struct DetailView: View {
        @Binding var showing: Bool
    
        var body: some View {
                Text("Detail")
                    .navigationBarItems(leading: Button("Back", action: { self.showing = false }))
        }
    }
    

提交回复
热议问题