Building Reusable Views

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

Open the starter project for this lesson and build and run the app. Tap the Flight Timeline button to bring up the timeline view. Right now, it shows a scrollable list of flight names and destinations.

Simple flight list view
Simple flight list view

In this lesson, you’ll start with this simple timeline view and then adapt it to a more reusable view that looks like this:

An improved and reusable flight list view
An improved and reusable flight list view

When building a complex view, you’ll find that starting with something simple and adding on will go faster than trying to do everything at once. First, you’ll work on the cards.

Inside the Timeline folder, create a new SwiftUI view named DepartureTimeView.swift and change the view and preview to:

struct DepartureTimeView: View {
  var flight: FlightInformation

  var body: some View {
    VStack {
      if flight.direction == .arrival {
        Text(flight.otherAirport)
      }
      Text(flight.departureTime, style: .time)
    }
  }
}

#Preview {
  DepartureTimeView(flight: FlightData.generateTestFlight(date: Date()))
}

This view displays the departure time for the flight, with the airport’s name above the departure time. Now, add a new SwiftUI view named ArrivalTimeView.swift in the same group and change it to:

struct ArrivalTimeView: View {
  var flight: FlightInformation

  var body: some View {
    VStack {
      if flight.direction == .departure {
        Text(flight.otherAirport)
      }
      Text(flight.arrivalTime, style: .time)
    }
  }
}

#Preview {
  ArrivalTimeView(flight: FlightData.generateTestFlight(date: Date()))
}

Now, return to FlightCardView.swift and add the following code inside the VStack after the HStack containing the flight’s statusBoardName:

HStack(alignment: .bottom) {
  DepartureTimeView(flight: flight)
  Spacer()
  ArrivalTimeView(flight: flight)
}
.padding(.bottom, 12.0)

This will show the two new views on the timeline and add some padding to the bottom of each row. Run the app, view the Flight Timeline, and you’ll see your changes.

Simple flight cards
Simple flight cards

In the next segment, you’ll continue to improve the flight timeline by adding a view that show’s each flight’s progress.

See forum comments
Download course materials from Github
Previous: Introduction Next: Showing Flight Progress