ViewLab

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

Contents

  1. NavigationStack
  2. NavigationLink: destination or value
  3. Passing the path to child screens
  4. Programmatic navigation: path arrays and NavigationPath
  5. NavigationSplitView
  6. TabView
  7. Page-style TabView: onboarding pagers
  8. Sheets and full-screen covers
  9. Alerts, confirmation dialogs and popovers
  10. Toolbars
  11. 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.

A list that pushes a detail screen. The title modifiers go on the views inside the stack.
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")
        }
    }
}
NavigationView (old)NavigationStack (iOS 16+)
StatusDeprecated in iOS 16Current
Programmatic navigationOne isActive Bool per link: hard to manageA path you can append to and clear
Deep links / pop to rootAwkwardSet the path array
Split view on iPadBuilt in, often by accident (.navigationViewStyle)Use NavigationSplitView explicitly

Try “NavigationStack” with live code →

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.

Root owns the path; each step receives a binding.
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
    }
}
What does this print?
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 true

Try “Passing the path to child screens” with live code →

Programmatic 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.

A typed path: [Route]. Setting the whole array pushes several screens at once.
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"]
true
What does this print?
var path = ["A", "B"]
path.append("C")
path.removeLast()
path.append("D")
print(path.last!, path.count)
Show the answer
D 3

NavigationPath: 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.

NavigationPath mixing three types. Pop to root by assigning a new, empty NavigationPath (or 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 typesOne typeAny mix of Hashable types
Read the elementsYes: path.last, path[0], loopsNo: only count and isEmpty
Push / popappend, removeLast()append, removeLast(), removeLast(k)
Pop to rootpath.removeAll() or path = []path = NavigationPath()
Save and restoreMake Route Codable and encode the arraypath.codable (when every element is Codable)
Choose whenScreens 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.com
Applying a deep link: replace the whole path. The app needs the URL scheme registered in its Info settings.
NavigationStack(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.

Two columns: the sidebar List's selection drives the detail column. Add 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")
            }
        }
    }
}
NavigationStackNavigationSplitView
LayoutOne screen at a time2 or 3 columns side by side (iPad/Mac)
On iPhoneStackCollapses to a stack
Driven byLinks and a pathList selection bindings
Typical appSettings, drill-down listsMail, Notes, Files

Try “NavigationSplitView” with live code →

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.

iOS 17 style: tabItem + tag, one NavigationStack per tab, selection switched 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)
        }
    }
}

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.

The iOS 18 Tab API, for comparison.
// 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

badge works on tab items and on List rows.
.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.

Try “TabView” with live code →

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.

Swipe or tap Next; the selection binding knows the current page.
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)
        }
    }
}

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:)
BindingBinding<Bool>Binding<Item?>, where Item: Identifiable
Shown whenThe Bool is trueThe optional is not nil
Content closure getsNothingThe unwrapped item
On dismiss SwiftUI setsThe Bool back to falseThe item back to nil
Use for"Add new" forms, settings"Edit this one", details of a tapped row

Detents and full-screen covers

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).

A sheet with its own NavigationStack (so it has a title bar and toolbar) that saves through a closure and dismisses itself.
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)
                }
            }
        }
    }
}

Try “Sheets and full-screen covers” with live code →

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.

Title, actions, then message. Any button closes the alert and sets the Bool back to false.
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.")
        }
    }
}

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.

Each button dismisses the dialog after its action runs. 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.

A popover that stays a popover on iPhone too.
Button("Info") { showingInfo = true }
    .popover(isPresented: $showingInfo) {
        Text("Cooking time includes preparation.")
            .padding()
            .presentationCompactAdaptation(.popover)
    }
PresentationLooks likeDismissed byUse for
.sheetCard sliding up; can stop at detentsSwipe down, or codeFocused task: add, edit, settings
.fullScreenCoverCovers the whole screenCode only (no swipe)Onboarding, camera, login
.alertSmall centred boxAny of its buttonsWarnings, confirming deletes
.confirmationDialogAction sheet from the bottom (iPhone)A button, or tapping outsideChoosing between actions
.popoverBubble with an arrow (iPad/Mac)Tapping outsideExtra info or small controls
Push (NavigationLink)Slides in from the rightBack button, swipe from the edgeDrilling 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.

Leading, trailing, principal (replaces the title) and a bottom bar group.
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") { }
            }
        }
}
PlacementWhere (iPhone)
.topBarLeadingLeft of the navigation bar (iOS 17; replaces .navigationBarLeading)
.topBarTrailingRight of the navigation bar (iOS 17; replaces .navigationBarTrailing)
.principalCentre of the navigation bar, in place of the title
.bottomBarA toolbar at the bottom of the screen
.cancellationAction / .confirmationActionSemantic: the system puts Cancel and Save/Done in the right places for each platform
.primaryActionThe most important action; trailing on iOS
.keyboardAbove 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.

Try “Toolbars” with live code →

Bug hunt: navigation

A two-tab gallery app with five planted mistakes. For each letter, say what the user would see (or what the compiler says) and how to fix it.

Five defects: one compile error, one crash, three wrong-behaviour bugs.
import SwiftUI

struct Artwork: Identifiable {                                   // [A]
    let id: Int
    let title: String
}

struct GalleryApp: View {
    var body: some View {
        NavigationStack {                                         // [B]
            TabView {
                GalleryList()
                    .tabItem { Label("Gallery", systemImage: "photo") }
                Text("Favourites")
                    .tabItem { Label("Favourites", systemImage: "heart") }
            }
        }
    }
}

struct GalleryList: View {
    @State private var path: [Artwork] = []
    let artworks = [Artwork(id: 1, title: "Harbour"), Artwork(id: 2, title: "Orchard")]

    var body: some View {
        List(artworks) { art in
            NavigationLink(art.title, value: art)               // [C]
        }
        .toolbar {
            Button("Back") { path.removeLast() }                // [D]
        }
    }
}

struct ArtworkDetail: View {
    @State var path: [Artwork]                                   // [E]
    let art: Artwork

    var body: some View {
        Button("Home") { path.removeAll() }
            .navigationTitle(art.title)
    }
}
Show the bugs
  • [A] NavigationLink(value:) and a typed path need a Hashable value. Artwork is only Identifiable: compile error. Fix: struct Artwork: Identifiable, Hashable.
  • [B] The whole TabView sits inside one NavigationStack: pushed screens cover the tab bar, and the tabs share one back history. Fix: Remove the outer stack and put a NavigationStack inside each tab.
  • [C] There is no .navigationDestination(for: Artwork.self) anywhere, and path isn't connected to any stack, so tapping a row does nothing (a runtime warning only). Fix: Wrap the List in NavigationStack(path: $path) and add .navigationDestination(for: Artwork.self) { ArtworkDetail(path: $path, art: $0) }.
  • [D] removeLast() on an empty path crashes at runtime, and at the root the path is always empty. Fix: if !path.isEmpty { path.removeLast() }, or remove the button: the stack already has a Back button.
  • [E] @State var path makes a private copy, so Home empties the copy and the stack doesn't move. Fix: @Binding var path: [Artwork], passed $path from GalleryList.

Try “Bug hunt: navigation” with live code →

Exam traps

Code or claimWhat really happens
NavigationViewDeprecated in iOS 16: use NavigationStack (or NavigationSplitView)
.navigationTitle on the NavigationStack itselfNo 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 stackMust be Hashable
.navigationDestination inside a List rowMay 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] pathpath.removeAll() (or path = [])
Pop to root with a NavigationPathpath = NavigationPath() or path.removeLast(path.count)
path.removeLast() on an empty pathRuntime crash: check isEmpty first
Read path[0] from a NavigationPathNot possible: it's type-erased, only count/isEmpty
Whole TabView inside one NavigationStackPushed screens cover the tab bar: put a stack inside each tab
.tag(0) with an enum selectionTag type doesn't match: selection never changes
Tab("Home", systemImage:value:)iOS 18 only; iOS 17 uses .tabItem + .tag
.sheet(item:) item typeMust be Identifiable; the binding is optional
fullScreenCoverNo swipe to dismiss: provide a button
dismiss read in the parent viewDismisses the parent, not the sheet
.presentationDetents on the presenting viewNo effect: put it on the sheet's content
.alert with no buttonsShows a single OK button
.toolbar on a view outside any NavigationStackTop-bar items don't appear
.navigationBarLeading / .navigationBarTrailingDeprecated: .topBarLeading / .topBarTrailing (iOS 17)
Child screen declares @State var path instead of @BindingIt edits a copy: the stack doesn't move
NavigationLink(destination:label:)Not deprecated; only isActive: and tag:selection: were
.navigationBarBackButtonHidden(true) with no other exitUser is stuck: add a button that edits the path or calls dismiss()
.tabViewStyle(.page) dots on a white pageInvisible: 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

  1. Which container replaced NavigationView for drill-down navigation in iOS 16?

    Show the answer

    NavigationStack

  2. 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.

  3. What must a value passed to NavigationLink(value:) conform to?

    Show the answer

    Hashable

  4. 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.

  5. 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].

  6. What is the main limitation of NavigationPath compared with [Route]?

    Show the answer

    You can't read its elements back

    It's type-erased: you get count, isEmpty, append and removeLast, but not the elements.

  7. What does this print?

    Show the answer

    ["A", "D"]

  8. 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.

  9. In iOS 17, how does a tab get a value for TabView(selection:)?

    Show the answer

    .tag(_:)

    Tab(value:) is the iOS 18 API.

  10. .sheet(item: $selected) requires selected to be…

    Show the answer

    An optional of an Identifiable type

  11. What happens to the item binding when the user swipes a sheet(item:) down?

    Show the answer

    SwiftUI sets it to nil

  12. Which presentation can't be dismissed by swiping down?

    Show the answer

    .fullScreenCover

  13. How does a presented sheet close itself?

    Show the answer

    Call dismiss() from @Environment(\.dismiss) inside the sheet

  14. Which modifier lets a sheet stop at half height?

    Show the answer

    .presentationDetents([.medium])

  15. In an alert, what does a button with role: .cancel do?

    Show the answer

    It runs when the user cancels and sits in the cancel position

  16. On iPhone, a .confirmationDialog appears as…

    Show the answer

    An action sheet from the bottom

  17. Which toolbar placement replaces the title in the centre of the navigation bar?

    Show the answer

    .principal

  18. What does ToolbarItemGroup(placement: .bottomBar) do?

    Show the answer

    Places several views together in the bottom toolbar

  19. Which is true of NavigationSplitView on iPhone?

    Show the answer

    It collapses into a single stack

  20. 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. @Bindable is for @Observable objects, not arrays.

  21. Which NavigationLink initializer is deprecated in iOS 16 and later?

    Show the answer

    NavigationLink(destination:isActive:label:)

  22. What does .tabViewStyle(.page) do to a TabView?

    Show the answer

    Shows swipeable full-width pages with index dots

  23. What does this print?

    Show the answer

    true

← Lists, observation and environment · Lifecycle, animation and persistence →

Practise this lesson interactively →