Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add Navigation to a List in SwiftUI
Written by Team Kodeco

Navigation is a critical aspect of any app. It allows users to move between different screens and provides an intuitive way to understand how various pieces of content are interrelated. SwiftUI, with its NavigationStack API, simplifies the process of implementing navigation within list-based interfaces.

To add navigation to a list in SwiftUI, the List needs to be embedded within a NavigationStack. Below, we create a simple example where we navigate from a list of parks to a detail view for each park.

Note: If you want to try out this example, you can download an archive of the park images here.

struct Park: Hashable {
  let name: String
  let imageName: String
  let description: String
}

extension Park: Identifiable {
  var id: String { name }
}

struct ContentView: View {
  @State private var presentedParks: [Park] = []

  var parks: [Park] {
    [
      Park(name: "Yosemite", imageName: "yosemite", description: "Yosemite National Park"),
      Park(name: "Sequoia", imageName: "sequoia", description: "Sequoia National Park"),
      Park(name: "Point Reyes", imageName: "point_reyes", description: "Point Reyes National Seashore")
    ]
  }

  var body: some View {
    NavigationStack(path: $presentedParks) {
      List(parks) { park in
        NavigationLink(park.name, value: park)
      }
      .navigationDestination(for: Park.self) { park in
        ParkDetailsView(park: park)
      }
    }
  }
}

struct ParkDetailsView: View {
  let park: Park

  var body: some View {
    VStack {
      Image(park.imageName)
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: 200, height: 200)
      Text(park.name)
        .font(.title)
        .foregroundColor(.primary)
      Text(park.description)
        .font(.body)
        .foregroundColor(.secondary)
    }
    .padding()
  }
}

Select Yosemite and your preview should now look like:

A List in a NavigationStack in SwiftUI.
A List in a NavigationStack in SwiftUI.

In this example, we’ve defined a Park structure, a ParkDetailsView for displaying details of the selected park, and a List of parks within a NavigationStack. When a park in the list is selected, the app navigates to the ParkDetailsView for the chosen park.

Remember to provide clear and intuitive navigation for your users. With SwiftUI’s powerful tools, you can customize the navigation bar and add buttons as needed. Explore the documentation and get creative with your design!

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.