Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
        }
}
like image 549
Seb Avatar asked Sep 05 '19 09:09

Seb


People also ask

How do I hide TabBar in SwiftUI?

If we want to hide the TabBar , we just write TabView into NavigationView , making the NavigationView the super-view and the TabView the child-view, which is just opposite to the above View Hierarchy .


2 Answers

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

like image 123
Enea Dume Avatar answered Sep 22 '22 06:09

Enea Dume


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

like image 27
Mojtaba Hosseini Avatar answered Sep 22 '22 06:09

Mojtaba Hosseini