SwiftUI Lists & Navigation
Most iPhone apps are built from two ingredients: scrolling lists of rows and navigation that pushes a detail screen when you tap a row. SwiftUI gives you List, ForEach and NavigationStack for exactly this.
Note: SwiftUI code can't run in the browser. The screens are shown as interactive HTML mocks, and the data handling is shown in runnable plain Swift.
Identifiable data
List and ForEach need to tell rows apart so they can animate insertions and deletions correctly. The easiest way is to make your model Identifiable — it just needs an id property:
struct Country: Identifiable {
let id: String // ISO code is unique, so it makes a good id
let name: String
let flag: String
let population: Double // millions
}
let countries = [
Country(id: "JP", name: "Japan", flag: "🇯🇵", population: 124.5),
Country(id: "BR", name: "Brazil", flag: "🇧🇷", population: 211.1),
Country(id: "NO", name: "Norway", flag: "🇳🇴", population: 5.5),
]
// What a List would display, sorted by name
for c in countries.sorted(by: { $0.name < $1.name }) {
print("\(c.flag) \(c.name) — \(c.population)M [id: \(c.id)]")
}🇧🇷 Brazil — 211.1M [id: BR]
🇯🇵 Japan — 124.5M [id: JP]
🇳🇴 Norway — 5.5M [id: NO]
Tip: If your data has no natural unique key, use
let id = UUID().
A List with navigation
Wrap the list in a NavigationStack, and make each row a NavigationLink. The link's destination is the view pushed onto the stack:
import SwiftUI
struct CountryList: View {
let countries: [Country]
var body: some View {
NavigationStack {
List(countries) { country in
NavigationLink {
CountryDetail(country: country)
} label: {
HStack {
Text(country.flag).font(.largeTitle)
Text(country.name)
}
}
}
.navigationTitle("Countries")
}
}
}
struct CountryDetail: View {
let country: Country
var body: some View {
VStack(spacing: 12) {
Text(country.flag).font(.system(size: 96))
Text("Population: \(country.population, specifier: "%.1f") million")
}
.navigationTitle(country.name)
}
}Tap a row in the mock to "push" the detail screen, then use the back button:
<div style="width:320px;height:460px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#f2f2f7;font-family:-apple-system,system-ui,sans-serif;overflow:hidden;position:relative">
<div id="list" style="padding:48px 0 0">
<div style="font-size:30px;font-weight:700;padding:0 16px 12px">Countries</div>
<div style="margin:0 16px;background:#fff;border-radius:10px" id="rows"></div>
</div>
<div id="detail" style="display:none;padding:48px 16px 0;text-align:center">
<div onclick="back()" style="color:#007aff;font-size:17px;text-align:left;cursor:pointer">‹ Countries</div>
<div id="dname" style="font-size:30px;font-weight:700;text-align:left;margin:8px 0 24px"></div>
<div id="dflag" style="font-size:96px"></div>
<div id="dpop" style="font-size:17px;margin-top:12px"></div>
</div>
</div>
<script>
const data = [['🇧🇷', 'Brazil', 211.1], ['🇯🇵', 'Japan', 124.5], ['🇳🇴', 'Norway', 5.5]];
document.getElementById('rows').innerHTML = data.map((c, i) =>
`<div onclick="open_(${i})" style="display:flex;align-items:center;gap:10px;padding:10px 16px;cursor:pointer;${i ? 'border-top:1px solid #e5e5ea' : ''}">
<span style="font-size:30px">${c[0]}</span><span style="flex:1;font-size:17px">${c[1]}</span><span style="color:#c7c7cc">›</span></div>`).join('');
function open_(i) {
const [f, n, p] = data[i];
const $ = (id) => document.getElementById(id);
$('dflag').textContent = f; $('dname').textContent = n; $('dpop').textContent = `Population: ${p.toFixed(1)} million`;
$('list').style.display = 'none'; $('detail').style.display = 'block';
}
function back() {
document.getElementById('detail').style.display = 'none';
document.getElementById('list').style.display = 'block';
}
</script>ForEach, sections and deletion
ForEach generates views from a collection. Combine it with Section for grouped lists, and .onDelete for swipe-to-delete:
struct ShoppingList: View {
@State private var items = ["Apples", "Bread", "Cheese"]
var body: some View {
NavigationStack {
List {
Section("To buy") {
ForEach(items, id: \.self) { item in
Text(item)
}
.onDelete { offsets in
items.remove(atOffsets: offsets)
}
}
}
.navigationTitle("Shopping")
.toolbar { EditButton() }
}
}
}.onDelete hands you an IndexSet of rows to remove. Here is the same data operation in runnable Swift (IndexSet comes from Foundation):
import Foundation
var items = ["Apples", "Bread", "Cheese", "Dates"]
let swiped = IndexSet([1, 3]) // user deleted "Bread" and "Dates"
for index in swiped.sorted(by: >) { // remove from the end so indexes stay valid
items.remove(at: index)
}
print(items)["Apples", "Cheese"]
Value-based navigation
For larger apps, push a value instead of a view and decide the destination in one place with .navigationDestination(for:):
NavigationStack {
List(countries) { country in
NavigationLink(country.name, value: country.id)
}
.navigationDestination(for: String.self) { code in
CountryDetail(country: lookup(code))
}
}| API | Purpose |
|---|---|
List |
scrolling, styled list of rows |
ForEach |
build views from a collection (inside List, stacks, …) |
Section("Title") |
group rows under a header |
NavigationStack |
container that manages a stack of screens |
NavigationLink |
a row/button that pushes a screen |
.navigationTitle(_:) |
title in the navigation bar |
.navigationDestination(for:) |
map pushed values to screens |
Test yourself
What does a type need to be used directly in List(items) { … }?
- Conform to
Codable - Conform to
Identifiable(have anid) - Be a class
- Conform to
View
Which container enables NavigationLink to push detail screens?
- VStack
- NavigationStack
- ScrollView
- TabView
What does the closure of .onDelete receive?
- The deleted item
- An IndexSet of row positions
- A Bool
- Nothing