Swift & SwiftUI course › Session 6
Navigation and presentation
How a SwiftUI app moves between screens: stacks, value-based links, paths you control in code, tabs, sheets, alerts and toolbars, with the exam traps around each.
About 40 minutes · covers NavigationStack, NavigationPath, TabView, sheets, alerts, toolbars
Open the interactive lesson (live previews, quizzes) →What you'll learn
- Build a NavigationStack with titles and links, and explain why NavigationView is deprecated
- Use value-based navigation with
NavigationLink(value:)and.navigationDestination(for:) - Drive navigation from code with a
[Route]array or aNavigationPath: push, pop and pop to root - Build a TabView with a tag-based selection and one stack per tab
- Choose between sheet, fullScreenCover, alert, confirmationDialog and popover, and dismiss them correctly
- Place toolbar buttons with ToolbarItem placements
Contents
- NavigationStack
- NavigationLink: destination or value
- Passing the path to child screens
- Programmatic navigation: path arrays and NavigationPath
- NavigationSplitView
- TabView
- Page-style TabView: onboarding pagers
- Sheets and full-screen covers
- Alerts, confirmation dialogs and popovers
- Toolbars
- Bug hunt: navigation
NavigationStack
A NavigationStack shows one root view and keeps a stack of views pushed on top of it. Pushing slides a new screen in from the right; the Back button (or a swipe from the left edge) pops it. It's the standard drill-down pattern: list, then detail. Available from iOS 16.
import SwiftUI
struct ContentView: View {
let subjects = ["Swift", "SwiftUI", "Data Structures"]
var body: some View {
NavigationStack {
List(subjects, id: \.self) { subject in
NavigationLink(subject) {
Text("Notes for \(subject)")
.navigationTitle(subject)
.navigationBarTitleDisplayMode(.inline)
}
}
.navigationTitle("Subjects")
}
}
}.navigationTitle("Subjects")sets the title shown in the navigation bar..navigationBarTitleDisplayMode(.large)is the big title that shrinks on scroll;.inlineis the small centred title;.automatic(the default) uses large on the root and inherits on pushed screens.- iOS 17 adds
.toolbarTitleDisplayMode(_:), which also offers.inlineLarge. Either modifier is fine for iOS 17.
| NavigationView (old) | NavigationStack (iOS 16+) | |
|---|---|---|
| Status | Deprecated in iOS 16 | Current |
| Programmatic navigation | One isActive Bool per link: hard to manage | A path you can append to and clear |
| Deep links / pop to root | Awkward | Set the path array |
| Split view on iPad | Built in, often by accident (.navigationViewStyle) | Use NavigationSplitView explicitly |
NavigationLink: destination or value
There are two ways to write a link. The destination form names the view to push right there. The value form only says which data to push; a separate .navigationDestination(for:) modifier says which view to build for that type of data.
// 1. Destination form: the view is written inside the link
NavigationLink("Pasta") {
RecipeDetail(recipe: pasta)
}
NavigationLink {
RecipeDetail(recipe: pasta)
} label: {
Label("Pasta", systemImage: "fork.knife")
}
// 2. Value form: the link carries a value...
NavigationLink("Pasta", value: pasta)
NavigationLink(value: pasta) {
Label("Pasta", systemImage: "fork.knife")
}
// ...and the stack maps that type to a view, once
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetail(recipe: recipe)
}struct Recipe: Identifiable, Hashable {
let id: Int
var name: String
var minutes: Int
}
struct RecipeList: View {
let recipes = [
Recipe(id: 1, name: "Dal tadka", minutes: 30),
Recipe(id: 2, name: "Poha", minutes: 15),
]
var body: some View {
NavigationStack {
List(recipes) { recipe in
NavigationLink(recipe.name, value: recipe)
}
.navigationTitle("Recipes")
.navigationDestination(for: Recipe.self) { recipe in
Text("\(recipe.name): \(recipe.minutes) minutes")
.navigationTitle(recipe.name)
}
}
}
}NavigationLink { Destination() } | NavigationLink(value:) + .navigationDestination(for:) | |
|---|---|---|
| Where the screen is decided | At every link | Once per data type, on the stack's content |
| When the destination view is created | When the link itself is built (the struct is made early, even if never tapped) | Only when the value is pushed |
Works with a path | No | Yes: the path holds the same values |
| Requirement on the data | None | The value must be Hashable |
| Best for | Tiny apps, one-off links | Real apps, deep links, programmatic navigation |
Why Hashable? The stack stores the pushed values and compares them to work out what changed, so each value must be Hashable (which includes Equatable). A struct gets Hashable synthesised if all its stored properties are Hashable; just write : Hashable. An enum without associated values is Hashable automatically; with associated values, write : Hashable and Swift synthesises it if every associated value is Hashable.
A route enum
Real apps push several kinds of screen. Wrap them in one Hashable enum, often called Route, and handle every case in a single .navigationDestination(for: Route.self). The switch must be exhaustive, so adding a new screen without handling it is a compile error, not a silent bug.
enum Route: Hashable {
case category(String)
case recipe(id: Int)
case settings
var title: String {
switch self {
case .category(let name): return "Category: \(name)"
case .recipe(let id): return "Recipe #\(id)"
case .settings: return "Settings"
}
}
}
let a = Route.recipe(id: 7)
let b = Route.recipe(id: 7)
let c = Route.recipe(id: 8)
print(a == b, a == c)
print(a.title, Route.settings.title)
var visits: [Route: Int] = [:]
visits[a, default: 0] += 1
visits[b, default: 0] += 1
print(visits[.recipe(id: 7)]!, visits.count)Output
true false
Recipe #7 Settings
2 1Equal routes have equal hashes, so a and b are the same dictionary key. That is exactly what Hashable promises and what the stack relies on.
enum Route: Hashable {
case category(String)
case recipe(id: Int)
case settings
}
func screenName(for route: Route) -> String {
switch route {
case .category(let name): return name
case .recipe(let id): return "Recipe \(id)"
}
}
print(screenName(for: .category("Desserts")))The switch doesn't handle .settings. Inside .navigationDestination(for: Route.self) this is the same error: every route needs a screen.
NavigationStack {
CategoryList()
.navigationDestination(for: Route.self) { route in
switch route {
case .category(let name): CategoryView(name: name)
case .recipe(let id): RecipeDetail(id: id)
case .settings: SettingsView()
}
}
}NavigationLink(destination:label:) is not deprecated
// Older spelling of the destination form: still valid in iOS 17
NavigationLink(destination: PlanetDetail(name: "Mars")) {
Label("Mars", systemImage: "globe")
}
// Deprecated (iOS 16): links driven by an isActive Bool or tag/selection
// NavigationLink(destination: PlanetDetail(name: "Mars"), isActive: $showMars) { ... }NavigationLink(destination:label:)and the trailing-closure formNavigationLink { Detail() } label: { ... }are the same idea and both are current API.- What changed in iOS 16 is programmatic navigation:
isActive:andtag:selection:were deprecated in favour of a path onNavigationStack. - The destination form builds the
PlanetDetailstruct as soon as the link is built. In a 500-row List that is 500 detail structs. Keep detailinits cheap, and do loading in.task, which runs only when the screen appears. - The value form defers that work and lets code push the same screen by appending to the path, which the destination form can't do.
Passing the path to child screens
The stack's root owns the path in @State. A pushed screen that needs to navigate in code (go to the next step, jump back to the start) gets a @Binding to the same path. A copy wouldn't work: changing a copy doesn't move the real stack.
enum CheckoutStep: Hashable {
case address, payment, confirmed
}
struct CheckoutRoot: View {
@State private var path: [CheckoutStep] = []
var body: some View {
NavigationStack(path: $path) {
Button("Start checkout") { path.append(.address) }
.navigationTitle("Basket")
.navigationDestination(for: CheckoutStep.self) { step in
switch step {
case .address: AddressStep(path: $path)
case .payment: PaymentStep(path: $path)
case .confirmed: ConfirmedStep(path: $path)
}
}
}
}
}
struct AddressStep: View {
@Binding var path: [CheckoutStep]
var body: some View {
Button("Continue to payment") { path.append(.payment) }
.navigationTitle("Address")
}
}
struct PaymentStep: View {
@Binding var path: [CheckoutStep]
var body: some View {
Button("Pay") { path.append(.confirmed) }
.navigationTitle("Payment")
}
}
struct ConfirmedStep: View {
@Binding var path: [CheckoutStep]
var body: some View {
VStack(spacing: 16) {
Text("Order confirmed")
Button("Back to basket") { path.removeLast(path.count) } // pop to root
}
.navigationTitle("Done")
.navigationBarBackButtonHidden(true) // no going back into a finished payment
}
}@Binding var pathin the child,$pathfrom the parent: both read and write one array.- Pop to root:
path.removeLast(path.count)orpath.removeAll()for an array;path = NavigationPath()orpath.removeLast(path.count)for aNavigationPath. .navigationBarBackButtonHidden(true)goes on the pushed view and hides its Back button (on iOS it also turns off the swipe-back gesture in typical use). Give the user another way out, like the button above.- For screens far down the tree, an
@Observablerouter object in the environment holding the path is an alternative to passing the binding through every level.
enum Step { case address, payment, confirmed }
var path: [Step] = []
path.append(.address)
path.append(.payment)
path.append(.confirmed)
print(path.count)
path.removeLast(path.count)
print(path.count, path.isEmpty)Show the answer
3
0 trueProgrammatic navigation: path arrays and NavigationPath
Give the stack a path binding and the path is the navigation state. The root view isn't in the path; every element is one pushed screen. Append to push, remove the last to pop, empty it to pop to root. The Back button changes the path for you too.
struct RecipesRoot: View {
@State private var path: [Route] = []
var body: some View {
NavigationStack(path: $path) {
List {
Button("Open Desserts") { path.append(.category("Desserts")) }
Button("Jump to recipe 42") {
path = [.category("Desserts"), .recipe(id: 42)]
}
}
.navigationTitle("Recipes")
.navigationDestination(for: Route.self) { route in
switch route {
case .category(let name):
Button("Show recipe 1 in \(name)") { path.append(.recipe(id: 1)) }
case .recipe(let id):
Button("Recipe \(id): back to start") { path.removeAll() }
case .settings:
Text("Settings")
}
}
}
}
}A path array is just a stack data structure. Here is the same logic in plain Swift:
var path: [String] = []
path.append("Desserts") // push
path.append("Gulab jamun") // push
print(path, path.count)
path.removeLast() // pop (like Back)
print(path)
path.append("Kheer")
path.append("Reviews")
path.removeLast(2) // pop two screens
print(path)
path.removeAll() // pop to root
print(path.isEmpty)Output
["Desserts", "Gulab jamun"] 2
["Desserts"]
["Desserts"]
truevar path = ["A", "B"]
path.append("C")
path.removeLast()
path.append("D")
print(path.last!, path.count)Show the answer
D 3NavigationPath: a type-erased path
A [Route] path can only hold Routes. NavigationPath is type-erased: it can hold values of different Hashable types at once (a Recipe, then an Int, then a String), each matched by its own .navigationDestination(for:). The cost: you can't read its elements back, only count them, append and remove.
path.removeLast(path.count)).struct BrowseView: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
List {
Button("Recipe: Poha") { path.append(Recipe(id: 2, name: "Poha", minutes: 15)) }
Button("Chef number 5") { path.append(5) }
Button("Tag: quick") { path.append("quick") }
}
.navigationTitle("Browse")
.navigationDestination(for: Recipe.self) { recipe in Text(recipe.name) }
.navigationDestination(for: Int.self) { id in Text("Chef \(id)") }
.navigationDestination(for: String.self) { tag in
VStack {
Text("Tag: \(tag) (depth \(path.count))")
Button("Back one") { path.removeLast() }
Button("Pop to root") { path = NavigationPath() }
}
}
}
}
}[Route] (typed array) | NavigationPath (type-erased) | |
|---|---|---|
| Element types | One type | Any mix of Hashable types |
| Read the elements | Yes: path.last, path[0], loops | No: only count and isEmpty |
| Push / pop | append, removeLast() | append, removeLast(), removeLast(k) |
| Pop to root | path.removeAll() or path = [] | path = NavigationPath() |
| Save and restore | Make Route Codable and encode the array | path.codable (when every element is Codable) |
| Choose when | Screens are known up front (most apps) | Independent modules push their own types |
Deep links into routes
A deep link is a URL that opens a specific screen, for example recipes://category/Desserts/recipe/42. Parse it into routes, then assign the result to the path. Parsing is plain Swift, so it's easy to test:
enum Route: Hashable {
case category(String)
case recipe(id: Int)
case settings
}
func routes(from link: String) -> [Route]? {
let scheme = "recipes://"
guard link.hasPrefix(scheme) else { return nil }
let parts = link.dropFirst(scheme.count).split(separator: "/").map { String($0) }
var result: [Route] = []
var i = 0
while i < parts.count {
switch parts[i] {
case "settings":
result.append(.settings)
i += 1
case "category" where i + 1 < parts.count:
result.append(.category(parts[i + 1]))
i += 2
case "recipe" where i + 1 < parts.count:
guard let id = Int(parts[i + 1]) else { return nil }
result.append(.recipe(id: id))
i += 2
default:
return nil
}
}
return result
}
func describe(_ route: Route) -> String {
switch route {
case .category(let name): return "category " + name
case .recipe(let id): return "recipe \(id)"
case .settings: return "settings"
}
}
for link in ["recipes://category/Desserts/recipe/42", "recipes://settings",
"recipes://recipe/abc", "https://example.com"] {
if let found = routes(from: link) {
print(found.map(describe))
} else {
print("invalid:", link)
}
}Output
["category Desserts", "recipe 42"]
["settings"]
invalid: recipes://recipe/abc
invalid: https://example.comNavigationStack(path: $path) {
// ...
}
.onOpenURL { url in
if let newPath = routes(from: url.absoluteString) {
path = newPath
}
}Try “Programmatic navigation: path arrays and NavigationPath” with live code →
NavigationSplitView
NavigationSplitView shows two or three columns side by side on iPad and Mac: a sidebar, an optional content column, and a detail column. On iPhone it collapses into a single stack automatically. Use it for list-plus-detail apps such as Mail or Notes.
content: between them for three columns.struct CatalogueSplit: View {
let departments = ["Computing", "Design", "Maths"]
@State private var selected: String?
var body: some View {
NavigationSplitView {
List(departments, id: \.self, selection: $selected) { name in
Text(name)
}
.navigationTitle("Departments")
} detail: {
if let selected {
Text("Courses in \(selected)")
} else {
Text("Choose a department")
}
}
}
}| NavigationStack | NavigationSplitView | |
|---|---|---|
| Layout | One screen at a time | 2 or 3 columns side by side (iPad/Mac) |
| On iPhone | Stack | Collapses to a stack |
| Driven by | Links and a path | List selection bindings |
| Typical app | Settings, drill-down lists | Mail, Notes, Files |
TabView
A TabView shows a tab bar at the bottom with one tab per top-level section of the app. Each child view is a tab; .tabItem gives its icon and label, and .tag gives it a value so a selection binding can read or change the current tab from code.
enum AppTab: Hashable {
case home, search, profile
}
struct RootView: View {
@State private var selection: AppTab = .home
var body: some View {
TabView(selection: $selection) {
NavigationStack {
Button("Go to Profile") { selection = .profile }
.navigationTitle("Home")
}
.tabItem { Label("Home", systemImage: "house") }
.tag(AppTab.home)
NavigationStack {
Text("Search").navigationTitle("Search")
}
.tabItem { Label("Search", systemImage: "magnifyingglass") }
.tag(AppTab.search)
NavigationStack {
Text("Profile").navigationTitle("Profile")
}
.tabItem { Label("Profile", systemImage: "person.crop.circle") }
.tag(AppTab.profile)
.badge(2)
}
}
}- The
tagvalue's type must match theselectiontype exactly:.tag(AppTab.home)with@State var selection: AppTab. - Put a
NavigationStackinside each tab, so each tab keeps its own back history. Don't wrap the wholeTabViewin one stack: pushed screens would cover the tab bar. .badge(2)or.badge("New")shows a badge on the tab.- Without
selection, the TabView manages the current tab itself; you only need the binding to switch tabs in code.
iOS 18 added a new Tab type: Tab("Home", systemImage: "house", value: AppTab.home) { HomeView() } inside TabView(selection:). It replaces .tabItem + .tag, but it isn't available on iOS 17, so iOS 17 apps use .tabItem.
// iOS 18 and later only
TabView(selection: $selection) {
Tab("Home", systemImage: "house", value: AppTab.home) {
HomeView()
}
Tab("Search", systemImage: "magnifyingglass", value: AppTab.search) {
SearchView()
}
}Badges
.tabItem { Label("Inbox", systemImage: "tray") }
.badge(unreadCount) // Int: a count of 0 shows no badge
.badge("New") // Text badge (a String)Prefer the Int form for counts: you don't have to hide the badge yourself when the count reaches zero.
Page-style TabView: onboarding pagers
TabView has a second look. With .tabViewStyle(.page) there is no tab bar: the children become full-width pages you swipe between, with page-index dots at the bottom. It is the usual way to build an onboarding carousel or a photo pager.
struct OnboardingPage: Identifiable {
let id: Int
let symbol: String
let headline: String
}
struct OnboardingView: View {
let pages = [
OnboardingPage(id: 0, symbol: "book", headline: "Track what you read"),
OnboardingPage(id: 1, symbol: "target", headline: "Set a yearly goal"),
OnboardingPage(id: 2, symbol: "chart.bar", headline: "See your progress"),
]
@State private var current = 0
var onFinish: () -> Void = {}
var body: some View {
VStack {
TabView(selection: $current) {
ForEach(pages) { page in
VStack(spacing: 20) {
Image(systemName: page.symbol).font(.system(size: 64))
Text(page.headline).font(.title2)
}
.tag(page.id) // Int tag matches Int selection
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
.indexViewStyle(.page(backgroundDisplayMode: .always)) // dots readable on white
Button(current == pages.count - 1 ? "Get started" : "Next") {
if current < pages.count - 1 {
withAnimation { current += 1 }
} else {
onFinish()
}
}
.buttonStyle(.borderedProminent)
.padding(.bottom)
}
}
}.tabViewStyle(.page)turns tabs into swipeable pages;.page(indexDisplayMode: .never)hides the dots..indexViewStyle(.page(backgroundDisplayMode: .always))puts a backdrop behind the dots, which are white by default and vanish on a white page..tabItemlabels are ignored in page style; use.tagwith aselectionbinding to know or change the page.- Show it once: store a flag such as
@AppStorage("seenOnboarding")and present the pager (for example in afullScreenCover) only while it's false.
Try “Page-style TabView: onboarding pagers” with live code →
Sheets and full-screen covers
A sheet slides a view up over the current screen, for a focused task such as adding an item. It is modal: it isn't part of the navigation stack and has no Back button. The user dismisses it by swiping down, or you dismiss it in code.
sheet(isPresented:) for a flag, sheet(item:) for an optional Identifiable item.struct RecipeListView: View {
@State private var showingAdd = false
@State private var selected: Recipe?
let recipes: [Recipe]
var body: some View {
List(recipes) { recipe in
Button(recipe.name) { selected = recipe }
}
.toolbar {
Button("Add", systemImage: "plus") { showingAdd = true }
}
// 1. Bool: show the same view whenever the flag is true
.sheet(isPresented: $showingAdd) {
Text("Add recipe form")
.presentationDetents([.medium, .large])
}
// 2. Item: show a view for a specific item; nil means hidden
.sheet(item: $selected) { recipe in
Text("Editing \(recipe.name)")
}
}
}.sheet(isPresented:) | .sheet(item:) | |
|---|---|---|
| Binding | Binding<Bool> | Binding<Item?>, where Item: Identifiable |
| Shown when | The Bool is true | The optional is not nil |
| Content closure gets | Nothing | The unwrapped item |
| On dismiss SwiftUI sets | The Bool back to false | The item back to nil |
| Use for | "Add new" forms, settings | "Edit this one", details of a tapped row |
Detents and full-screen covers
.presentationDetents([.medium, .large])lets the sheet stop at half or full height (iOS 16). Also.fraction(0.25)and.height(200). Apply it to the sheet's content, not to the presenting view..presentationDragIndicator(.visible)shows the grab bar..interactiveDismissDisabled()stops swipe-to-dismiss, for example while a form has unsaved changes..fullScreenCover(isPresented:)(anditem:) covers the whole screen and can't be swiped away: you must give the user a button that dismisses it. Use it for onboarding, a camera or a login flow.
Dismissing with @Environment(\.dismiss)
The presented view dismisses itself by reading the dismiss action from the environment and calling it. It works for sheets, full-screen covers and pushed screens (it pops).
struct AddRecipeView: View {
@Environment(\.dismiss) private var dismiss
@State private var name = ""
let onSave: (String) -> Void
var body: some View {
NavigationStack {
Form {
TextField("Recipe name", text: $name)
}
.navigationTitle("New Recipe")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
onSave(name)
dismiss()
}
.disabled(name.isEmpty)
}
}
}
}
}Alerts, confirmation dialogs and popovers
An alert is a small centred box with a title, an optional message and buttons. Use it for important information or to confirm a destructive action. Like a sheet, it is driven by a Bool binding.
struct CourseRow: View {
let title: String
@State private var showingDelete = false
var body: some View {
Button("Delete \(title)", role: .destructive) {
showingDelete = true
}
.alert("Delete course?", isPresented: $showingDelete) {
Button("Delete", role: .destructive) { print("deleted") }
Button("Cancel", role: .cancel) { }
} message: {
Text("\(title) will be removed. This can't be undone.")
}
}
}- Button roles:
.destructiveis drawn in red;.cancelis placed in the cancel position and runs when the user cancels. - If you give no buttons, the alert shows a single OK button.
alert(_:isPresented:presenting:actions:message:)passes an optional piece of data into the actions and message, likesheet(item:).- The message closure may contain only
Text.
confirmationDialog
A confirmation dialog offers several choices about an action the user just started. On iPhone it appears as an action sheet that slides up from the bottom; on iPad it appears as a popover.
titleVisibility: .visible shows the title..confirmationDialog("Share recipe", isPresented: $showingShare, titleVisibility: .visible) {
Button("Copy link") { }
Button("Send to Meera") { }
Button("Remove from list", role: .destructive) { }
}popover
A popover is a small bubble pointing at the view that opened it. It appears as a popover on iPad and Mac. In a compact width (iPhone) it adapts into a sheet unless you add .presentationCompactAdaptation(.popover) (iOS 16.4) to the popover's content.
Button("Info") { showingInfo = true }
.popover(isPresented: $showingInfo) {
Text("Cooking time includes preparation.")
.padding()
.presentationCompactAdaptation(.popover)
}| Presentation | Looks like | Dismissed by | Use for |
|---|---|---|---|
.sheet | Card sliding up; can stop at detents | Swipe down, or code | Focused task: add, edit, settings |
.fullScreenCover | Covers the whole screen | Code only (no swipe) | Onboarding, camera, login |
.alert | Small centred box | Any of its buttons | Warnings, confirming deletes |
.confirmationDialog | Action sheet from the bottom (iPhone) | A button, or tapping outside | Choosing between actions |
.popover | Bubble with an arrow (iPad/Mac) | Tapping outside | Extra info or small controls |
| Push (NavigationLink) | Slides in from the right | Back button, swipe from the edge | Drilling into detail |
Try “Alerts, confirmation dialogs and popovers” with live code →
Toolbars
.toolbar { } adds buttons to the navigation bar or the bottom bar. Like the title, it is attached to a view inside a NavigationStack (or a sheet's own stack). Wrap each item in ToolbarItem(placement:) to choose where it goes; a bare Button inside .toolbar uses the default (trailing) position.
NavigationStack {
List(notes, id: \.self) { Text($0) }
.navigationTitle("Notes")
.toolbar {
ToolbarItem(placement: .topBarLeading) {
EditButton()
}
ToolbarItem(placement: .topBarTrailing) {
Button("Add", systemImage: "plus") { addNote() }
}
ToolbarItem(placement: .principal) {
Text("My Notes").font(.headline)
}
ToolbarItemGroup(placement: .bottomBar) {
Button("Archive", systemImage: "archivebox") { }
Spacer()
Text("\(notes.count) notes")
Spacer()
Button("Share", systemImage: "square.and.arrow.up") { }
}
}
}| Placement | Where (iPhone) |
|---|---|
.topBarLeading | Left of the navigation bar (iOS 17; replaces .navigationBarLeading) |
.topBarTrailing | Right of the navigation bar (iOS 17; replaces .navigationBarTrailing) |
.principal | Centre of the navigation bar, in place of the title |
.bottomBar | A toolbar at the bottom of the screen |
.cancellationAction / .confirmationAction | Semantic: the system puts Cancel and Save/Done in the right places for each platform |
.primaryAction | The most important action; trailing on iOS |
.keyboard | Above the keyboard while a text field is focused |
ToolbarItemGroup puts several views in one placement, in order. Spacer() inside a group pushes items apart, which is how bottom bars are laid out.
Exam traps
| Code or claim | What really happens |
|---|---|
NavigationView | Deprecated in iOS 16: use NavigationStack (or NavigationSplitView) |
.navigationTitle on the NavigationStack itself | No title: put it on a view inside the stack |
NavigationLink(value:) with no matching .navigationDestination(for:) | Tapping does nothing (a runtime warning, no compile error) |
| Value type pushed onto a stack | Must be Hashable |
.navigationDestination inside a List row | May be ignored: attach it outside lazy containers |
NavigationLink { Detail() } | The Detail struct is created when the link is built, even if never tapped |
Pop to root with a [Route] path | path.removeAll() (or path = []) |
Pop to root with a NavigationPath | path = NavigationPath() or path.removeLast(path.count) |
path.removeLast() on an empty path | Runtime crash: check isEmpty first |
Read path[0] from a NavigationPath | Not possible: it's type-erased, only count/isEmpty |
Whole TabView inside one NavigationStack | Pushed screens cover the tab bar: put a stack inside each tab |
.tag(0) with an enum selection | Tag type doesn't match: selection never changes |
Tab("Home", systemImage:value:) | iOS 18 only; iOS 17 uses .tabItem + .tag |
.sheet(item:) item type | Must be Identifiable; the binding is optional |
fullScreenCover | No swipe to dismiss: provide a button |
dismiss read in the parent view | Dismisses the parent, not the sheet |
.presentationDetents on the presenting view | No effect: put it on the sheet's content |
.alert with no buttons | Shows a single OK button |
.toolbar on a view outside any NavigationStack | Top-bar items don't appear |
.navigationBarLeading / .navigationBarTrailing | Deprecated: .topBarLeading / .topBarTrailing (iOS 17) |
Child screen declares @State var path instead of @Binding | It edits a copy: the stack doesn't move |
NavigationLink(destination:label:) | Not deprecated; only isActive: and tag:selection: were |
.navigationBarBackButtonHidden(true) with no other exit | User is stuck: add a button that edits the path or calls dismiss() |
.tabViewStyle(.page) dots on a white page | Invisible: add .indexViewStyle(.page(backgroundDisplayMode: .always)) |
Viva questions and answers
What is NavigationStack?
A container that shows a root view and a stack of views pushed on top of it, with a navigation bar and Back button. It replaced NavigationView in iOS 16.
Why was NavigationView deprecated?
Programmatic navigation needed one isActive Bool per link, which made deep links and pop-to-root awkward. NavigationStack keeps the whole stack in a single path you control, and split layouts moved to NavigationSplitView.
Explain value-based navigation.
NavigationLink(value:) pushes a piece of data, and .navigationDestination(for: Type.self) on the stack maps that type to a view. It separates what to show from how to show it and works with a path.
Why must navigation values be Hashable?
The stack stores and compares the pushed values to know what changed and to keep identity. Hashable gives equality and a hash for that.
NavigationPath vs an array path?
An array like [Route] holds one type and you can read its elements. NavigationPath is type-erased: it can hold several Hashable types, but you can only append, remove and count.
How do you pop to root programmatically?
Clear the path: path.removeAll() for an array, or path = NavigationPath() for a NavigationPath. The root view isn't in the path, so an empty path shows it.
How would you handle a deep link?
Parse the URL in .onOpenURL into an array of routes, and assign it to the stack's path. The stack then pushes all those screens at once.
When would you use NavigationSplitView?
For list-detail apps on iPad and Mac, with a sidebar and detail (and optionally a content column). On iPhone it collapses into a stack automatically.
How do you switch tabs from code?
Give TabView a selection binding and .tag each tab with a value of the same type, usually an enum. Setting the bound variable switches the tab.
sheet(isPresented:) vs sheet(item:)?
isPresented takes a Bool and shows the same view. item takes an optional Identifiable value, shows the sheet when it's non-nil, and passes the unwrapped value to the content closure. SwiftUI resets the binding on dismiss.
sheet vs fullScreenCover?
A sheet is a card the user can swipe away and can stop at detents. A full-screen cover hides everything and can only be dismissed from code, so you must provide a button.
How does a view dismiss itself?
Read @Environment(\.dismiss) private var dismiss inside the presented view and call dismiss(). It closes a sheet or cover, or pops a pushed screen.
Alert vs confirmationDialog?
An alert is a centred box for important messages or confirming one action. A confirmation dialog offers a set of choices for an action the user started; on iPhone it's an action sheet from the bottom.
What are button roles?
.destructive marks a dangerous action, drawn in red. .cancel marks the cancel action, placed in the standard cancel position. The system uses roles for styling and layout.
How do you add buttons to the navigation bar?
Use .toolbar on a view inside the stack, with ToolbarItem(placement: .topBarTrailing) and similar placements. ToolbarItemGroup puts several items in one placement.
What is the iOS 18 Tab API?
Tab("Home", systemImage: "house", value: .home) { HomeView() } inside TabView. It replaces .tabItem and .tag, but needs iOS 18, so iOS 17 apps use .tabItem.
How does a pushed screen navigate the stack itself?
The root keeps the path in @State and passes $path down; the child declares @Binding var path. Appending pushes, removeLast() pops, and removeLast(path.count) or removeAll() returns to the root. For deep trees an @Observable router in the environment can hold the path instead.
Is the destination form of NavigationLink deprecated?
No. NavigationLink(destination:label:) and its trailing-closure spelling are current. The deprecated ones are the isActive: and tag:selection: initializers, replaced by a path on NavigationStack. The destination form builds the destination struct eagerly, so keep its init cheap.
How would you build an onboarding carousel?
A TabView with .tabViewStyle(.page), one tagged page per step, a selection binding so a Next button can advance it, and .indexViewStyle(.page(backgroundDisplayMode: .always)) if the dots need a backdrop. Show it once by checking an @AppStorage flag.
When would you hide the Back button?
When going back would be wrong, such as after a payment is confirmed. .navigationBarBackButtonHidden(true) on the pushed view hides it, and you must provide another exit, for example a button that clears the path.
Quiz
Which container replaced
NavigationViewfor drill-down navigation in iOS 16?Show the answer
NavigationStack
Where should
.navigationTitle("Recipes")be attached?Show the answer
On a view inside the NavigationStack
The stack reads the title from the screen it is currently showing.
What must a value passed to
NavigationLink(value:)conform to?Show the answer
Hashable
A link uses
value: recipe.id(an Int). Which destination handles it?Show the answer
.navigationDestination(for: Int.self)
Destinations are matched by the exact type of the pushed value.
With
@State var path: [Route] = [], how do you pop to the root?Show the answer
path.removeAll()
The root isn't in the path, so an empty path shows the root.
NavigationPath()is the wrong type for a[Route].What is the main limitation of
NavigationPathcompared with[Route]?Show the answer
You can't read its elements back
It's type-erased: you get
count,isEmpty,appendandremoveLast, but not the elements.What does this print?
Show the answer
["A", "D"]
Where should the NavigationStacks go in a tabbed app?
Show the answer
One stack inside each tab
Each tab keeps its own history, and pushed screens don't hide the tab bar.
In iOS 17, how does a tab get a value for
TabView(selection:)?Show the answer
.tag(_:)
Tab(value:)is the iOS 18 API..sheet(item: $selected)requiresselectedto be…Show the answer
An optional of an Identifiable type
What happens to the
itembinding when the user swipes asheet(item:)down?Show the answer
SwiftUI sets it to nil
Which presentation can't be dismissed by swiping down?
Show the answer
.fullScreenCover
How does a presented sheet close itself?
Show the answer
Call
dismiss()from@Environment(\.dismiss)inside the sheetWhich modifier lets a sheet stop at half height?
Show the answer
.presentationDetents([.medium])
In an alert, what does a button with
role: .canceldo?Show the answer
It runs when the user cancels and sits in the cancel position
On iPhone, a
.confirmationDialogappears as…Show the answer
An action sheet from the bottom
Which toolbar placement replaces the title in the centre of the navigation bar?
Show the answer
.principal
What does
ToolbarItemGroup(placement: .bottomBar)do?Show the answer
Places several views together in the bottom toolbar
Which is true of
NavigationSplitViewon iPhone?Show the answer
It collapses into a single stack
A pushed screen must pop back to the root. How should it receive the root's
@State var path: [Step]?Show the answer
@Binding var path: [Step]A binding writes to the root's array.
@Bindableis for@Observableobjects, not arrays.Which NavigationLink initializer is deprecated in iOS 16 and later?
Show the answer
NavigationLink(destination:isActive:label:)What does
.tabViewStyle(.page)do to a TabView?Show the answer
Shows swipeable full-width pages with index dots
What does this print?
Show the answer
true
← Lists, observation and environment · Lifecycle, animation and persistence →
Practise this lesson interactively →