TabView 选择重置为工作表演示文稿上的第一个选项卡

ors*_*aef 7 ios tabview swift swiftui

更新:

感谢 Harshil 和 Sumit 指出我太愚蠢了,没有意识到我正在使用id()而不是tag(). 如果说你能从这个问题中学到什么,那就是:

当你独自完成一个项目时,你往往会变得盲目。你看不到自己的错误。进行代码审查。请朋友和同事查看一下。这是个好主意。;)

原问题:

在我的 SwiftUI 项目中,我使用BindingTabView$selection以编程方式切换选项卡。

问题是:例如,当我在上呈现工作表时,TabView选择中包含的第二个视图将重置为第一个选项卡。

对我来说,这似乎是一个SwiftUI 错误- 但有解决方法吗?

下面您可以找到一个演示该行为的工作示例。(使用Xcode 12.4测试)

如何测试:转到第二个选项卡,点击“二”按钮,您将看到返回到第一个选项卡。一旦您selection从 TabView 中删除该属性,这种情况就不会再发生。

奥兰多干杯

enum TabPosition: Hashable {
    case one
    case two
    case three
}

struct RootView: View {
    
    @State private var selection: TabPosition = .one
    
    var body: some View {
        TabView(selection: $selection) {
            One()
                .tabItem { Label("One", systemImage: "1.circle") }
                .id(TabPosition.one)
            Two()
                .tabItem { Label("Two", systemImage: "2.circle") }
                .id(TabPosition.two)
            Three()
                .tabItem { Label("Three", systemImage: "3.circle") }
                .id(TabPosition.three)
        }
    }
}


struct One: View {
    var body: some View {
        Text("One").padding()
    }
}

struct Two: View {
    
    @State var isPresented = false
    
    var body: some View {
        Button("Two") { isPresented.toggle() }
        .sheet(isPresented: $isPresented, content: {
            Three()
        })
    }
}

struct Three: View {
    var body: some View {
        Text("Three").padding()
    }
}

Run Code Online (Sandbox Code Playgroud)

Har*_*tel 4

.tag()像这样使用:

struct ContentView: View {
    @State private var selection = 1
    var body: some View {
        TabView(selection: $selection) {
            One()
                .tabItem { Label("One", systemImage: "1.circle") }
                .tag(1)
            Two()
                .tabItem { Label("Two", systemImage: "2.circle") }
                .tag(2)
            Three()
                .tabItem { Label("Three", systemImage: "3.circle") }
                .tag(3)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)