SwiftUI Navigation

Jun 20 2024 · Swift 5.9, iOS 17.0, Xcode 15.0

Lesson 02: Hierarchical Navigation Structures

Demo

Episode complete

Play next episode

Next

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

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

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

Unlock now

Passing Data Between Views in Hierarchical Navigation

First, you’ll create a class to add to the environment. Under the Models group, create a new file named FlightNavigationInfo.swift. Change the file to read:

import SwiftUI

class FlightNavigationInfo: ObservableObject {
  @Published var lastFlightId: Int?
}
@StateObject var lastFlightInfo = FlightNavigationInfo()
.environmentObject(lastFlightInfo)
case showLastFlight
if
  let flightId = lastFlightInfo.lastFlightId,
  let flight = flightInfo.getFlightById(flightId) {
  buttons.append(
    ViewButton(
      id: .showLastFlight,
      title: "\(flight.flightName)",
      subtitle: "The Last Flight You Viewed"
    )
  )
}
case .showLastFlight:
  if
    let flightId = lastFlightInfo.lastFlightId,
    let flight = flightInfo.getFlightById(flightId) {
    FlightDetails(flight: flight)
  }
@EnvironmentObject var lastFlightInfo: FlightNavigationInfo
.onAppear {
  lastFlightInfo.lastFlightId = flight.id
}
.environmentObject(FlightNavigationInfo())

Three-Column Navigation

Your current navigation structure contains a sidebar with the app’s top-level navigation structure. For the Flight Status view, you display a NavigationStack for the details view. In this case, you know that your structure contains three columns: the top-level navigation, the list of flights, and the details for a single flight. That makes it a good candidate for the three-column version of the NavigationSplitView.

@State private var selectedFlight: Int?
} detail: {
  if let flightId = selectedFlight,
    let flight = FlightData().getFlightById(flightId) {
    FlightDetails(flight: flight)
  }
}
@Binding var selectedFlight: Int?
List(shownFlights, selection: $selectedFlight) { flight in
FlightList(
  flights: flightInfo.flights,
  selectedFlight: $selectedFlight
)
let flightId = lastFlightInfo.lastFlightId,
let flightId = selectedFlight,
See forum comments
Cinema mode Download course materials from Github
Previous: Hierarchical Navigation Structures Next: Conclusion