加载并尝试了编程选项卡选择的简单示例(有效)后,我很困惑为什么它在我的代码中不起作用。因此,我一步步简化了代码,以消除其他可能性,现在它非常简单,几乎与工作示例相同,当然,我的应用程序特有的任何方面都已被删除。但它仍然不起作用。这是代码:
struct MyTabView: View {
@State private var selTab = 1
var body: some View {
TabView(selection: $selTab) {
Button("Goto Tab 2") { selTab = 2 }
.tabItem { Label("Tab1", systemImage: "list.dash") }
Text("Tab 2")
.tabItem { Label("Tab2", systemImage: "list.dash") }
}
}
}
struct ContentView: View {
var body: some View {
MyTabView()
}
}
当我按下“Goto Tab 2”按钮时,屏幕闪烁,但页面没有变化。考虑到苹果文档的状态,这并没有多大帮助。我完全困惑为什么这段代码不起作用,而通过谷歌找到的简单示例却可以,当它们看起来几乎相同时
您应该为每个选项卡分配一个
tag
,例如:
TabView(selection: $selTab) {
Button("Goto Tab 2") { selTab = 2 }
.tabItem { Label("Tab1", systemImage: "list.dash") }
.tag(1) // 👈
Text("Tab 2")
.tabItem { Label("Tab2", systemImage: "list.dash") }
.tag(2) // 👈
}