Reputation: 1686
I have a TabView
in SwiftUI
and want the second tab to be the default, when starting the app.
I haven't found any documentation to provide this behavior, but it should be possible. Most of the apps have the mid tab as their default tab.
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")
}
}
Upvotes: 31
Views: 11762
Reputation: 119458
Define a State
with the default value and bind it to TabView
:
@State var selection = 1
,,,
TabView(selection: $selection)
,,,
Then assign a tag
to each tabItem
:
,,,
.tabItem {
Image(systemName: "bolt.horizontal.fill")
Text("Trend")
}.tag(1)
,,,
Now you can use them together, selection
=== tag
Upvotes: 9
Reputation: 4409
We can use enum
with specific View
name cases for tag
rather than using Int
s.
func tag<V>(_ tag: V) -> some View where V : Hashable
Please note that tag
has to be confirmed to Hashable protocol so you can the enum cases like below.
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)
}
Upvotes: 4
Reputation: 3232
@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)
}
In this case I set default selected the third Tab
. Change selection
to the desired Tab
.
Upvotes: 53