28

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")
        }
}
Enea Dume
  • 3,014
  • 3
  • 21
  • 36
Seb
  • 1,586
  • 1
  • 11
  • 15

3 Answers3

39
@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.

Enea Dume
  • 3,014
  • 3
  • 21
  • 36
9

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

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
3

We can use enum with specific View name cases for tag rather than using Ints.

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)
}
Sateesh Yemireddi
  • 4,289
  • 1
  • 20
  • 37
  • 1
    This should be the accepted answer. Much cleaner than using ints. Though you don't necessarily need `String, CaseIterable, Identifiable`, just `Hashable` is enough. – Lord Zsolt Apr 15 '23 at 12:31