Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a TabView with Lists in SwiftUI
Written by Team Kodeco

Creating a TabView with lists in SwiftUI provides a neat way to navigate between different sections of content with ease. It is a common pattern in many mobile apps and can greatly enhance your app’s user interface.

Here is an example of how you might create a TabView with two different lists of animals and plants:

struct ContentView: View {
  var animals = ["Lion", "Tiger", "Elephant", "Leopard"]
  var plants = ["Rose", "Lily", "Tulip", "Orchid"]

  var body: some View {
    TabView {
      List(animals, id: \.self) { animal in
        Text(animal)
      }
      .tabItem {
        Image(systemName: "hare")
        Text("Animals")
      }

      List(plants, id: \.self) { plant in
        Text(plant)
      }
      .tabItem {
        Image(systemName: "leaf")
        Text("Plants")
      }
    }
  }
}

Here’s what your preview should look like:

A list with swipe actions in SwiftUI.
A list with swipe actions in SwiftUI.

In this example, you create a TabView with two tabs. Each tab is represented by a List that contains different data — one for animals and one for plants. The tabs are labeled using the tabItem modifier and include an icon along with a text description.

In the “Animals” tab, you display a list of animal names, while in the “Plants” tab, you display a list of plant names. You use the List view’s initializer, which accepts a data collection and an id for uniquely identifying the elements. The row content is then provided in a closure, displaying each element as a Text view.

By creating a TabView with each tab displaying unique content, you can create a clean and easy-to-navigate user interface. Test this implementation in your SwiftUI project to see how it enhances your app’s navigational flow.

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.