swiftswiftuitabview

How to set a default Tab in SwiftUIs TabView?


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")
        }
}

Solution

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