TabView 在切换选项卡时重置导航堆栈 [英] TabView resets navigation stack when switching tabs

查看:22
本文介绍了TabView 在切换选项卡时重置导航堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 TabView:

I have a simple TabView:

TabView {
    NavigationView {
        VStack {
            NavigationLink(destination: Text("Detail")) {
                Text("Go to detail")
            }
        }
    }
        .tabItem { Text("First") }
        .tag(0)
    Text("Second View")
        .tabItem { Text("Second") }
        .tag(1)
}

当我转到选项卡 1 上的详细信息视图时,切换到选项卡 2,然后切换回选项卡 1,我假设返回到详细信息视图(iOS 中随处可见的基本 UX).相反,它会重置为选项卡 1 的根视图.

When I go to the detail view on tab 1, switch to tab 2 then switch back to tab 1 I would assume to go back to the detail view (a basic UX found everywhere in iOS). Instead it resets to the root view of tab 1.

由于 SwiftUI 不支持开箱即用,我该如何解决这个问题?

Since SwiftUI doesn't look to support this out of the box, how do I work around this?

推荐答案

这里有一个简单的例子,说明如何在根目录下为带有项目列表的导航堆栈保留状态:

Here's a simple example of how to preserve state for a navigation stack with a list of items at the root:

struct ContentView: View {

    var body: some View {

        TabView {

            Text("First tab")
                .tabItem { Image(systemName: "1.square.fill"); Text("First") }
                .tag(0)

            SecondTabView()
                .tabItem { Image(systemName: "2.square.fill"); Text("Second") }
                .tag(1)
        }
    }
}

struct SecondTabView: View {

    private struct ListItem: Identifiable {
        var id = UUID()
        let title: String
    }

    private let items = (1...10).map { ListItem(title: "Item #\($0)") }

    @State var selectedItemIndex: Int? = nil

    var body: some View {

        NavigationView {
            List(self.items.indices) { index in
                NavigationLink(destination:  Text(self.items[index].title),
                               tag: index,
                               selection: self.$selectedItemIndex) {
                    Text(self.items[index].title)
                }
            }
            .navigationBarTitle("Second tab", displayMode: .inline)
        }
    }
}

这篇关于TabView 在切换选项卡时重置导航堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆