Let's create a SwiftUI view that simulates an airport departure board!
We'll break this down into a few parts:
- Data Model: A
struct to represent a single flight, and an enum for flight status.
- Row View: A
View for displaying a single flight's information.
- Header View: A
View for the column headers.
- Main Departure Board View: The
ContentView that combines everything, manages the list of flights, and includes some basic animation for updates.
We'll aim for a classic digital/monospaced look.
1. Flight Data Model
First, let's define our data.
import Foundation // For Date and UUID
// MARK: - Flight Status Enum
enum FlightStatus: String, CaseIterable {
case onTime = "On Time"
case delayed = "Delayed"
case boarding = "Boarding"
case finalCall = "Final Call"
case departed = "Departed"
case canceled = "Canceled"
// Helper to get a color for the status
var color: Color {
switch self {
case .onTime, .departed: return .green
case .boarding, .finalCall: return .orange
case .delayed, .canceled: return .red
}
}
}
// MARK: - Flight Model
struct Flight: Identifiable {
let id = UUID()
var scheduledTime: Date
let flightNumber: String
let destination: String
var gate: String
var status: FlightStatus
// Helper to format time nicely
var formattedTime: String {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter.string(from: scheduledTime)
}
// Static method to generate some dummy data
static func mockFlights() -> [Flight] {
var flights: [Flight] = []
let now = Date()
let calendar = Calendar.current
// Add 10-15 random flights
for i in 0..<Int.random(in: 10...15) {
let hourOffset = Double.random(in: -2...3) // Some flights in past, some in future
let minuteOffset = Double.random(in: 0...59)
let time = calendar.date(byAdding: .minute, value: Int(hourOffset * 60 + minuteOffset), to: now)!
let flightNumber = ["UA", "DL", "AA", "BA", "LH"].randomElement()! + String(Int.random(in: 100...999))
let destination = ["New York", "London", "Paris", "Tokyo", "Dubai", "Los Angeles", "Chicago", "Frankfurt", "Singapore", "Sydney"].randomElement()!
let gate = Character(UnicodeScalar(Int.random(in: 65...70))!).description + String(Int.random(in: 1...30)) // A1-F30
// Random initial status
let initialStatus: FlightStatus
if time < now.addingTimeInterval(-60 * 30) { // More than 30 mins ago
initialStatus = Bool.random() ? .departed : .canceled
} else if time < now.addingTimeInterval(60 * 15) { // Within next 15 mins
initialStatus = [.boarding, .finalCall, .delayed].randomElement()!
} else {
initialStatus = .onTime
}
flights.append(Flight(
scheduledTime: time,
flightNumber: flightNumber,
destination: destination,
gate: gate,
status: initialStatus
))
}
// Sort by scheduled time
return flights.sorted { $0.scheduledTime < $1.scheduledTime }
}
}
2. Flight Row View
This view will display a single row on our departure board.
import SwiftUI
struct FlightRowView: View {
let flight: Flight
var body: some View {
HStack {
Text(flight.formattedTime)
.font(.custom("Menlo", size: 16)) // Monospaced for digital feel
.frame(width: 60, alignment: .leading)
Text(flight.flightNumber)
.font(.custom("Menlo", size: 16))
.frame(width: 80, alignment: .leading)
Text(flight.destination)
.font(.custom("Menlo", size: 16))
.frame(maxWidth: .infinity, alignment: .leading)
Text(flight.gate)
.font(.custom("Menlo", size: 16))
.frame(width: 50, alignment: .center)
Text(flight.status.rawValue)
.font(.custom("Menlo", size: 16))
.foregroundColor(flight.status.color) // Dynamic color based on status
.frame(width: 100, alignment: .leading)
}
.padding(.vertical, 4)
.padding(.horizontal)
// Ensure the row uses the overall board's dark background
.background(Color.clear)
}
}
// MARK: - Preview
struct FlightRowView_Previews: PreviewProvider {
static var previews: some View {
FlightRowView(flight: Flight.mockFlights().first!)
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
}
}
3. Departure Board Header View
This view will display the static column headers.
import SwiftUI
struct DepartureBoardHeaderView: View {
var body: some View {
HStack {
Text("TIME")
.frame(width: 60, alignment: .leading)
Text("FLIGHT")
.frame(width: 80, alignment: .leading)
Text("DESTINATION")
.frame(maxWidth: .infinity, alignment: .leading)
Text("GATE")
.frame(width: 50, alignment: .center)
Text("STATUS")
.frame(width: 100, alignment: .leading)
}
.font(.caption.bold())
.padding(.horizontal)
.padding(.bottom, 5)
.foregroundColor(.white.opacity(0.7)) // Slightly lighter for headers
.background(Color.black.opacity(0.3)) // Slight background for headers
}
}
// MARK: - Preview
struct DepartureBoardHeaderView_Previews: PreviewProvider {
static var previews: some View {
DepartureBoardHeaderView()
.preferredColorScheme(.dark)
.previewLayout(.sizeThatFits)
}
}
4. Main Departure Board View (ContentView)
This is the main view that holds everything together. It will manage the state of the flights and simulate real-time updates using a Timer.
import SwiftUI
struct ContentView: View {
@State private var flights: [Flight] = Flight.mockFlights()
// Timer to simulate updates every few seconds
let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
var body: some View {
VStack(spacing: 0) {
Text("Departures")
.font(.largeTitle.bold())
.foregroundColor(.white)
.padding(.bottom, 10)
DepartureBoardHeaderView()
List {
ForEach(flights) { flight in
FlightRowView(flight: flight)
.listRowSeparator(.hidden) // Hide default List separators
.listRowBackground(Color.clear) // Transparent background for rows
}
}
.listStyle(.plain) // Remove default List styling
.scrollContentBackground(.hidden) // Make List content background transparent
}
.background(Color.black.edgesIgnoringSafeArea(.all)) // Dark background for the entire board
.preferredColorScheme(.dark) // Ensure dark mode is preferred
.onReceive(timer) { _ in
updateRandomFlight()
}
}
// MARK: - Flight Update Logic
private func updateRandomFlight() {
guard !flights.isEmpty else { return }
// Filter out flights that are already departed or canceled, as they shouldn't change
let mutableFlights = flights.filter { $0.status != .departed && $0.status != .canceled }
guard var randomFlight = mutableFlights.randomElement(),
let index = flights.firstIndex(where: { $0.id == randomFlight.id }) else { return }
var updatedFlight = randomFlight
// Simulate status transitions
switch updatedFlight.status {
case .onTime:
// 20% chance of delay, 80% chance of boarding
if Bool.random() && Bool.random() { // Roughly 25% chance
updatedFlight.status = .delayed
updatedFlight.scheduledTime = updatedFlight.scheduledTime.addingTimeInterval(Double.random(in: 15*60...60*60)) // Add 15-60 min delay
updatedFlight.gate = "G" + String(Int.random(in: 1...30)) // New gate
} else {
updatedFlight.status = .boarding
}
case .delayed:
// Delayed flights can eventually board or be canceled
if Bool.random() {
updatedFlight.status = .boarding
} else {
updatedFlight.status = .canceled
}
case .boarding:
updatedFlight.status = .finalCall
case .finalCall:
updatedFlight.status = .departed
case .departed, .canceled:
// These states are final, no changes needed
return
}
// Apply the update
flights[index] = updatedFlight
// Re-sort the flights after an update (especially if time changed)
flights.sort { $0.scheduledTime < $1.scheduledTime }
}
}
// MARK: - Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
How to Use:
- Create a new SwiftUI project in Xcode.
- Replace the contents of your
ContentView.swift file with the code provided for ContentView, FlightRowView, DepartureBoardHeaderView, and the Flight model/enum. You can put them all in ContentView.swift for simplicity, or create separate files for Flight.swift, FlightRowView.swift, and DepartureBoardHeaderView.swift if you prefer.
- Run the app on a simulator or device.
You'll see a dark-themed departure board with flights updating their statuses periodically!