Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Tab View in SwiftUI
Written by Team Kodeco

Tab views are a great way to organize content and navigation options in your app. In SwiftUI, creating a tab view is straightforward using TabView.

Each tab within a TabView is a TabItem. Each TabItem should have a unique tag value, and should contain the content that you want displayed when that tab is selected.

Here’s an example with two tabs:

struct ContentView: View {
  var body: some View {
    TabView {
      Text("Tab 1's a star!")
        .tabItem {
          Image(systemName: "star")
          Text("Tab 1")
        }.tag(1)

      Text("Show the love for Tab 2!")
        .tabItem {
          Image(systemName: "heart")
          Text("Tab 2")
        }.tag(2)
    }
  }
}

Your preview should look like this:

SwiftUI provides TabView and TabItem views that work together.
SwiftUI provides TabView and TabItem views that work together.

In the above example, each TabItem contains an Image and Text view. The Image view displays an icon in the tab, while the Text view displays the title of the tab. The .tag(1) and .tag(2) modifiers set a unique identifier for each TabItem.

You can add as many tabs as you’d like to the TabView and customize their appearance in various ways. Once you’ve added all your tabs and configured them to your liking, you can present the TabView using a NavigationView or other view in your app.

That’s it! With just a few lines of SwiftUI code, you can create a tab view in your app to easily navigate between multiple screens.

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.