Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Switch Tabs Programmatically in SwiftUI
Written by Team Kodeco

Have you ever wanted to switch tabs in a tab view programmatically? Maybe you want to show a certain tab based on some user action or state change. In SwiftUI, this is easily achievable using the selection binding.

First, make sure your tab view has a selection binding that can be updated dynamically. For example, you might have a state variable called selectedTab:

struct ContentView: View {
  @State private var selectedTab: Int = 0

  var body: some View {
    VStack {
      Button("Switch to second tab") {
        selectedTab = 1
      }
      .padding()

      TabView(selection: $selectedTab) {
        Text("First Tab")
          .tabItem {
            Image(systemName: "1.circle")
            Text("Tab 1")
          }
          .tag(0)

        Text("Second Tab")
          .tabItem {
            Image(systemName: "2.circle")
            Text("Tab 2")
          }
          .tag(1)
      }
    }
  }
}

Your preview should look like this:

Use a selection binding to programmatically switch tabs in SwiftUI.
Use a selection binding to programmatically switch tabs in SwiftUI.

In this code, the ContentView has a state variable selectedTab that keeps track of which tab is currently selected. You use the TabView with a selection binding to selectedTab to update the tab based on the state variable. The tags in the tab items correspond to the possible values of selectedTab.

There is also a button at the top of the view. When this button is tapped, it sets selectedTab to 1, which corresponds to the second tab. This makes the TabView switch to the second tab programmatically.

And that’s it! Just like pressing a button on a remote control changes the channel, updating the selectedTab binding changes the current tab being displayed. With just a few lines of code, you can switch tabs programmatically in SwiftUI.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.