TabView in SwiftUI

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Using Tabbed Navigation

Open the starter project for this lesson. You’ll recognize it as the project from lesson two changed back to a two-column view. In this lesson, you’ll adapt the list of flights to take advantage of tabs to view different versions of the flight list quickly.

struct FlightList: View {
  var flights: [FlightInformation]
  @State private var path: [FlightInformation] = []

  var body: some View {
    NavigationStack(path: $path) {
      List(flights, id: \.id) { flight in
        NavigationLink(flight.statusBoardName, value: flight)
      }
      .navigationDestination(
        for: FlightInformation.self,
        destination: { flight in
          FlightDetails(flight: flight)
        }
      )
    }
  }
}
FlightList(
  flights: FlightData.generateTestFlights(date: Date())
)
// 1
TabView {
  // 2
  FlightList(
    flights: shownFlights.filter { $0.direction == .arrival }
  )
  // 3
  .tabItem {
    // 4
    Image("descending-airplane")
      .resizable()
    Text("Arrivals")
  }

  FlightList(flights: shownFlights)
  .tabItem {
    Image(systemName: "airplane")
      .resizable()
    Text("All")
  }
  
  FlightList(
    flights: shownFlights.filter { $0.direction == .departure }
  )
  .tabItem {
    Image("ascending-airplane")
    Text("Departures")
  }
}
.navigationTitle("Today's Flight Status")
.navigationBarItems(
  trailing: Toggle("Hide Past", isOn: $hidePast)
)
Flight status with tabs
Zfafql sxezum hakr qerw

Programmatically Tracking Tabs

When the user leaves and exits the new tabbed view, the app will always start back on the Arrivals tab. Remembering the last viewed tab would be a good interface change. To implement that, in FlightStatusBoard.swift, below the hidePast state variable, add the following line:

@AppStorage("FlightStatusCurrentTab") var selectedTab = 1
.tag(0)
.tag(1)
.tag(2)
TabView(selection: $selectedTab) {
Storing and recalling the last tab viewed
Vfizejr axh xusevqitt vsi xakw huw puevur

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo