[英]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 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
。
使用默认值定义一个State
并将其绑定到TabView
:
@State var selection = 1
,,,
TabView(selection: $selection)
,,,
然后为每个tabItem
分配一个tag
:
,,,
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}.tag(1)
,,,
现在可以一起使用了, selection
=== tag
我们可以将enum
与特定的View
名称案例一起用于tag
,而不是使用Int
s。
func tag<V>(_ tag: V) -> some View where V : Hashable
请注意,必须将tag
确认为 Hashable 协议,以便您可以像下面这样枚举案例。
enum Tab: String, CaseIterable, Identifiable {
case question
case data
case empty
var id: Self { self }
}
@State private var tab = Tab.data
TabView(selection: $tab) {
QuestionView()
.tabItem {
Image(systemName: "questionmark")
Text("Questions")
}
.tag(Tab.question)
DataView()
.tabItem {
Image(systemName: "chart.bar.fill")
Text("Data")
}
.tag(Tab.data)
Text("Empty Tab right now")
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}
.tag(Tab.empty)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.