如何在 SwiftUIs TabView 中设置默认选项卡?
How to set a default Tab in SwiftUIs TabView?
我在 SwiftUI
中有一个 TabView
并希望在启动应用程序时将第二个选项卡设置为默认选项卡。
我还没有找到任何文档来提供这种行为,但它应该是可能的。大多数应用程序都将中间选项卡作为其默认选项卡。
TabView {
QuestionView()
.tabItem {
Image(systemName: "questionmark")
Text("Questions")
}
DataView()
.tabItem {
Image(systemName: "chart.bar.fill")
Text("Data")
}
Text("Empty Tab right now")
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}
}
用默认值定义一个State
并绑定到TabView
:
@State var selection = 1
,,,
TabView(selection: $selection)
,,,
然后给每个tabItem
分配一个tag
:
,,,
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}.tag(1)
,,,
现在可以一起使用了,selection
=== tag
@State private var selection = 3
TabView(selection:$selection) {
QuestionView()
.tabItem {
Image(systemName: "questionmark")
Text("Questions")
}
.tag(1)
DataView()
.tabItem {
Image(systemName: "chart.bar.fill")
Text("Data")
}
.tag(2)
Text("Empty Tab right now")
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}
.tag(3)
}
在这种情况下,我设置默认选择第三个 Tab
。将 selection
更改为所需的 Tab
.
我在 SwiftUI
中有一个 TabView
并希望在启动应用程序时将第二个选项卡设置为默认选项卡。
我还没有找到任何文档来提供这种行为,但它应该是可能的。大多数应用程序都将中间选项卡作为其默认选项卡。
TabView {
QuestionView()
.tabItem {
Image(systemName: "questionmark")
Text("Questions")
}
DataView()
.tabItem {
Image(systemName: "chart.bar.fill")
Text("Data")
}
Text("Empty Tab right now")
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}
}
用默认值定义一个State
并绑定到TabView
:
@State var selection = 1
,,,
TabView(selection: $selection)
,,,
然后给每个tabItem
分配一个tag
:
,,,
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}.tag(1)
,,,
现在可以一起使用了,selection
=== tag
@State private var selection = 3
TabView(selection:$selection) {
QuestionView()
.tabItem {
Image(systemName: "questionmark")
Text("Questions")
}
.tag(1)
DataView()
.tabItem {
Image(systemName: "chart.bar.fill")
Text("Data")
}
.tag(2)
Text("Empty Tab right now")
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}
.tag(3)
}
在这种情况下,我设置默认选择第三个 Tab
。将 selection
更改为所需的 Tab
.