如何在SwiftUIs TabView中设置默认选项卡?

时间:2019-09-05 09:30:29

标签: swift swiftui tabview

我在TabView中有一个SwiftUI,并希望在启动应用程序时将第二个选项卡作为默认选项卡。

我还没有找到任何文档来提供这种行为,但是应该可以的。大多数应用程序将“中间”标签作为其默认标签。

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

2 个答案:

答案 0 :(得分:3)

@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

答案 1 :(得分:1)

使用默认值定义State并将其绑定到TabView

@State var selection = 1
,,,

    TabView(selection: $selection) 

,,,

然后为每个tag分配一个tabItem

,,,
    .tabItem {
        Image(systemName: "bolt.horizontal.fill")
        Text("Trend")
    }.tag(1)
,,,

现在您可以一起使用它们,selection === tag

相关问题