Building the User Interface

The previous chapter settled where data lives. This one is about the screen itself: how you get from one screen to another, how you present lists and data entry, how you pop up something on top of what the user is looking at, how you lay out things the built-in containers do not cover, how you animate a change so that it reads as motion rather than as a jump, and how you make sure the result works for a person who cannot see the screen, cannot read small text, or is using the app in direct sunlight. None of this is decoration. A screen that cannot be navigated is a screen that cannot be used, and a screen that ignores Dynamic Type is a screen that a meaningful number of people cannot use at all.

The code here targets Swift 5.9 and iOS 17 or later, so it uses NavigationStack, the Layout protocol, Canvas, TimelineView and the Observation framework. Where an older API is still common in existing codebases it is named in passing.

1. Composing a screen from custom views

A screen is a hierarchy of small views, each of which owns one idea. The size of a view is not a matter of taste; it is the difference between a screen you can change in one place and a screen you have to change in nine.

struct MessageRow: View {
    let message: Message

    var body: some View {
        HStack(alignment: .top, spacing: 12) {
            Avatar(initials: message.author.initials)
                .frame(width: 40, height: 40)

            VStack(alignment: .leading, spacing: 4) {
                Text(message.author.name)
                    .font(.headline)

                Text(message.body)
                    .font(.subheadline)
                    .foregroundStyle(.secondary)
                    .lineLimit(2)
            }

            Spacer(minLength: 8)

            Text(message.sentAt, style: .time)
                .font(.caption)
                .foregroundStyle(.tertiary)
        }
        .padding(.vertical, 4)
    }
}

MessageRow knows about a message and nothing else. It does not know whether it is inside a list, in a navigation destination, or in a preview. That isolation is what makes it reusable, and it is also what makes it testable, since a view that can be constructed with a plain value can be exercised without any navigation at all.

Three habits keep this decomposition honest. Give every view a name that describes what it shows rather than where it sits. Keep the data a view needs in its initialiser, so the view can be constructed in a preview without any setup. And push the styling decisions up to the caller with a custom modifier, so that two screens using the same row can style it differently.

2. Navigation

NavigationStack is the container that owns a path of screens. It is the only navigation container you should be starting new code with; NavigationView is the older one and remains in a great deal of existing code.

struct InboxView: View {
    var body: some View {
        NavigationStack {
            List {
                MessageRow(message: Message.sample)
            }
            .navigationTitle("Inbox")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

Two pieces of vocabulary matter. The navigation title is what appears in the bar, and the display mode decides whether it is large and prominent or small and inline. Toolbar buttons go in a ToolbarItem, and the placement values were renamed in iOS 17.

.toolbar {
    ToolbarItem(placement: .topBarTrailing) {
        Button {
            showComposer = true
        } label: {
            Label("Compose", systemImage: "square.and.pencil")
        }
    }

    ToolbarItem(placement: .topBarLeading) {
        EditButton()
    }
}

A NavigationLink inside a List row pushes a destination. There are two forms and one of them is preferred.

// Preferred from iOS 16: the destination is a value, not a view.
NavigationLink(value: Route.detail(message)) {
    MessageRow(message: message)
}
// Older form: the destination is built eagerly, every time.
NavigationLink {
    MessageDetailView(message: message)
} label: {
    MessageRow(message: message)
}

The value-based form is preferred because it decouples the link from the destination, lets you declare all destinations in one place, and makes the path a piece of state you can inspect, save, or drive from a deep link.

NavigationStack(path: $path) {
    MessageListView()
        .navigationDestination(for: Route.self) { route in
            switch route {
            case .detail(let message):
                MessageDetailView(message: message)
            case .settings:
                SettingsView()
            }
        }
}

Because NavigationLink(value:) pushes a value rather than a view, the row is not rebuilt when the stack changes, and the destination is not created until you navigate to it.

3. Lists, forms, and sections

List is for collections of rows. It is lazy, it handles selection, it supports swipe actions, and it adapts to the platform conventions for the current device.

List(items, selection: $selection) { item in
    NavigationLink(value: item) {
        Text(item.title)
    }
    .swipeActions(edge: .trailing) {
        Button("Delete", role: .destructive) {
            delete(item)
        }
    }
}

Form is for grouped data entry. It uses the same row grammar as List but renders with the inset grouped background and the form controls behave as expected.

Form {
    Section("Profile") {
        TextField("Name", text: $name)
        TextField("Email", text: $email)
            .keyboardType(.emailAddress)
            .textInputAutocapitalization(.never)
    }

    Section {
        Toggle("Receive updates", isOn: $wantsUpdates)
        Picker("Theme", selection: $theme) {
            Text("System").tag(Theme.system)
            Text("Light").tag(Theme.light)
            Text("Dark").tag(Theme.dark)
        }
    } header: {
        Text("Preferences")
    } footer: {
        Text("Appearance follows the system setting unless you choose otherwise.")
    }
}

Section is the grouping primitive, and it comes in three shapes. Section("Title") { ... } puts the title above the content, Section { ... } header: { ... } gives you full control over the header, and Section { ... } footer: { ... } adds explanatory text below. A section without a header is used purely to separate groups of rows.

Rows can be adjusted individually, which is how you build a list that does not look like a list.

.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
.listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))

The list style is chosen with a modifier: .listStyle(.insetGrouped) is the default on iOS, .plain removes the grouped background, and .sidebar is for macOS and iPadOS.

4. Controls

Form controls in SwiftUI are consistent to a fault: they all take a binding, and the label is optional or positional depending on the control.

Toggle switches between two states and can be a switch or a button.

Toggle("Notifications", isOn: $notificationsEnabled)
    .tint(.accentColor)

Toggle(isOn: $isOn) {
    Label("Airplane mode", systemImage: "airplane")
}

Picker chooses one value from a set. The style decides how it looks.

Picker("Sort", selection: $sort) {
    Text("Title").tag(Sort.title)
    Text("Author").tag(Sort.author)
}
.pickerStyle(.segmented)     // or .menu, .wheel, .inline

The tag modifier is not optional decoration. Without it the picker has no way to match a row to a value, and the selection silently fails to update.

Slider picks a value in a range. The label form takes a closure so the current value can be shown.

Slider(value: $volume, in: 0...1, step: 0.05) {
    Text("Volume")
} minimumValueLabel: {
    Image(systemName: "speaker.fill")
} maximumValueLabel: {
    Image(systemName: "speaker.wave.3.fill")
}

Stepper increments and decrements a value, or flips a boolean.

Stepper(value: $quantity, in: 1...20) {
    Text("Quantity: \(quantity)")
}

Stepper("Repeat weekly", isOn: $repeatsWeekly)

TextField has a value-formatting variant that is worth preferring when the input is numeric, because it gives the user the right keyboard and rejects nonsense.

TextField("Amount", value: $amount, format: .number)
    .keyboardType(.decimalPad)

5. Presenting something on top

There are three mechanisms for presenting temporary UI, and they differ in how destructive they feel.

A sheet slides up from the bottom and is used for a focused task. It is the modal of choice.

.sheet(isPresented: $showComposer) {
    ComposerView()
}

If the presented thing is a piece of data rather than a mode, use the item variant, which presents only when there is something to present and dismisses itself when the item is cleared.

.sheet(item: $selectedMessage) { message in
    MessageDetailView(message: message)
}

An alert is a small interruption with a clear question attached to it.

.alert("Delete this draft?", isPresented: $showDeleteAlert) {
    Button("Delete", role: .destructive) { deleteDraft() }
    Button("Cancel", role: .cancel) { }
} message: {
    Text("This cannot be undone.")
}

A confirmation dialog is the heavier variant, for decisions that need more than a single line of explanation or more than two options.

.confirmationDialog("How should we sort?", isPresented: $showSortOptions, titleVisibility: .visible) {
    Button("By title") { sort = .title }
    Button("By author") { sort = .author }
    Button("Cancel", role: .cancel) { }
}

The role parameter matters: .destructive renders the button in red, and .cancel positions it correctly and gives it the right behaviour under VoiceOver. Always give a destructive action a .destructive role, and always give the way out a .cancel role.

6. Custom layout with the Layout protocol

The built-in stacks cover most needs, but when they do not, iOS 16 gave you a way to write your own layout algorithm that participates properly in the SwiftUI layout system.

A Layout conformance has two requirements: one that says how big the layout wants to be, and one that says where each subview goes.

struct DiagonalLayout: Layout {
    func sizeThatFits(
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Void
    ) -> CGSize {
        let width = proposal.width ?? 100
        let height = proposal.height ?? 100
        return CGSize(width: width, height: height)
    }

    func placeSubviews(
        in bounds: CGRect,
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Void
    ) {
        for (index, subview) in subviews.enumerated() {
            let offset = CGFloat(index) * 24
            subview.place(
                at: CGPoint(x: bounds.minX + offset, y: bounds.minY + offset),
                anchor: .topLeading,
                proposal: .unspecified
            )
        }
    }
}

Used like any other container.

DiagonalLayout {
    Text("One")
    Text("Two")
    Text("Three")
}

The Layout protocol is genuinely useful when the layout depends on the size of the container, because the algorithm can be given a cache for work that would otherwise be repeated on every pass.

struct GridLayout: Layout {
    struct Cache {
        var frames: [CGRect] = []
    }

    func makeCache(subviews: Subviews) -> Cache { Cache() }

    func sizeThatFits(
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Cache
    ) -> CGSize {
        let columns = 2
        let rows = Int(ceil(Double(subviews.count) / Double(columns)))
        return CGSize(width: proposal.width ?? 320, height: proposal.height ?? CGFloat(rows) * 44)
    }

    func placeSubviews(
        in bounds: CGRect,
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Cache
    ) {
        for (index, subview) in subviews.enumerated() {
            let column = index % 2
            let row = index / 2
            let origin = CGPoint(
                x: bounds.minX + CGFloat(column) * (bounds.width / 2),
                y: bounds.minY + CGFloat(row) * 44
            )
            subview.place(at: origin, anchor: .topLeading, proposal: .unspecified)
        }
    }
}

When you need to switch between layouts at runtime, AnyLayout erases the concrete type.

@State private var isGrid = false

var layout = isGrid ? AnyLayout(GridLayout()) : AnyLayout(HStackLayout())

layout {
    ForEach(items) { item in
        Text(item.title)
    }
}

7. Measuring with GeometryReader

GeometryReader reports the size and position of the view that contains it. It is useful for things that genuinely depend on geometry, such as drawing a chart or positioning an element relative to another.

GeometryReader { proxy in
    VStack {
        Text("Width: \(Int(proxy.size.width))")
        Text("Height: \(Int(proxy.size.height))")
    }
    .frame(width: proxy.size.width, height: proxy.size.height, alignment: .topLeading)
}

GeometryReader has a reputation for causing trouble, and the reason is worth remembering: it is greedy. It accepts whatever size is proposed and fills it, so a GeometryReader in the middle of a VStack will consume all the remaining space and push its siblings out. The reliable pattern is to use it in a background layer, or to give it an explicit frame.

Circle()
    .fill(.blue)
    .frame(width: 100, height: 100)
    .background {
        GeometryReader { proxy in
            Text("Centre at \(Int(proxy.frame(in: .local).midX))")
                .font(.caption)
        }
    }

Before reaching for it, check whether a Layout or a simple GeometryReader in the background can answer the question. A GeometryReader at the top level of a screen is usually a sign that the layout is being fought rather than described.

8. Drawing with Canvas

Canvas is an immediate-mode drawing surface, available from iOS 15. It is the right tool for charts, graphs, and anything made of shapes rather than controls.

Canvas { context, size in
    let radius = min(size.width, size.height) / 4
    let centre = CGPoint(x: size.width / 2, y: size.height / 2)

    var path = Path()
    path.addArc(
        center: centre,
        radius: radius,
        startAngle: .degrees(0),
        endAngle: .degrees(270),
        clockwise: false
    )
    path.closeSubpath()

    context.stroke(path, with: .color(.accentColor), lineWidth: 4)
}
.frame(width: 200, height: 200)

The closure is called once per frame with the current size, and the drawing commands are recorded and rendered efficiently. Text can be drawn too.

Canvas { context, size in
    let resolved = context.resolve(Text("Total").font(.caption))
    context.draw(resolved, at: CGPoint(x: size.width / 2, y: 20))
}

Because the canvas redraws on demand, you have to tell it when something changed. Canvas has an rendersAsynchronously variant and an onDraw closure for content that depends on state.

9. Animating with TimelineView and matchedGeometryEffect

TimelineView schedules redraws on a schedule of your choosing, which is how you animate something that is not driven by a state change, such as a clock hand or a pulsing glow.

TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { context in
    let seconds = context.date.timeIntervalSinceReferenceDate
    let angle = Angle.degrees(seconds.truncatingRemainder(dividingBy: 60) * 6)

    Image(systemName: "clock")
        .font(.system(size: 64))
        .rotationEffect(angle)
}

The schedule comes in three flavours: .animation redraws as fast as the display allows, .periodic(from:by:) redraws on a fixed interval, and .periodic is driven by the display refresh rate.

matchedGeometryEffect animates one view into the position and shape of another. It is the trick behind shared-element transitions, and it needs a namespace to pair the two views.

struct ShapeSwitcher: View {
    @Namespace private var namespace
    @State private var isCircle = false

    var body: some View {
        ZStack {
            if isCircle {
                Circle()
                    .fill(.blue)
                    .matchedGeometryEffect(id: "shape", in: namespace)
            } else {
                RoundedRectangle(cornerRadius: 12)
                    .fill(.blue)
                    .matchedGeometryEffect(id: "shape", in: namespace)
            }
        }
        .frame(width: 120, height: 120)
        .onTapGesture {
            withAnimation(.spring(response: 0.4, dampingFraction: 0.8)) {
                isCircle.toggle()
            }
        }
    }
}

The id must be unique within the namespace, and both views must use the same id. If nothing animates, the usual cause is that the transition is not inside a withAnimation block.

10. Animation, and the two ways to ask for it

There are two mechanisms, and they are not interchangeable.

withAnimation wraps a state change and animates everything that changes as a result.

withAnimation(.easeInOut(duration: 0.25)) {
    isExpanded.toggle()
}

.animation(_:value:) attaches an animation to a view and triggers it when a specific value changes. It is safer, because it cannot animate something unrelated that happened to change in the same transaction.

Circle()
    .fill(isActive ? .green : .gray)
    .animation(.easeInOut(duration: 0.25), value: isActive)

The rule of thumb is: prefer .animation(_:value:) when the animation belongs to one view, and use withAnimation when a change in one place should animate a chain of changes across several views.

The animation values worth knowing are .default, .easeInOut, .linear, .spring, .bounce, .smooth and .snappy. Springs are usually the right answer for interface motion, because they settle rather than stop abruptly.

withAnimation(.spring(response: 0.4, dampingFraction: 0.8, blendDuration: 0.2)) {
    offset = .zero
}

Transitions control what happens to a view that is inserted or removed.

if isVisible {
    DetailPanel()
        .transition(.move(edge: .trailing).combined(with: .opacity))
}

Transitions only run when the surrounding change is animated, so withAnimation and .transition go together.

11. Accessibility

Accessibility in SwiftUI is mostly a matter of providing information that the system cannot infer. The system can infer that a Button is a button, but it cannot know what your icon-only button does.

Button {
    toggleFavourite()
} label: {
    Image(systemName: isFavourite ? "heart.fill" : "heart")
}
.accessibilityLabel(isFavourite ? "Remove from favourites" : "Add to favourites")
.accessibilityHint("Double tap to update your saved list")
.accessibilityValue(isFavourite ? "Favourite" : "Not a favourite")

accessibilityLabel replaces the label, accessibilityHint describes what happens when the element is activated, and accessibilityValue reports the current state of something that changes.

Container views often expose their children badly, so you can control that explicitly.

HStack {
    Image(systemName: "star.fill")
    Text("4.8")
}
.accessibilityElement(children: .combine)
.accessibilityLabel("Rating 4.8 out of 5")

Other useful modifiers are accessibilityHidden(true) to remove decorative content from the accessibility tree, accessibilityAddTraits(.isSelected) to report a selection state, and accessibilityAction(named:) to add a named custom action.

The system also exposes the user’s preferences, and a good app responds to them.

@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
@Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor

var body: some View {
    Content()
        .animation(reduceMotion ? nil : .spring(), value: isExpanded)
}

Reduce Motion is not optional. If a user has asked the system to reduce motion, your animations should stop, not merely become slower.

12. Dark mode and Dynamic Type

Dark mode is mostly a matter of using semantic colours. Color.primary, Color.secondary, Color(.systemBackground) and Color(.secondarySystemBackground) all adapt to the current appearance, while a hard-coded Color.white does not.

VStack {
    Text("Title")
        .foregroundStyle(.primary)
    Text("Subtitle")
        .foregroundStyle(.secondary)
}
.padding()
.background(Color(.secondarySystemBackground))

For colours you define yourself, put them in the asset catalogue with an Any and a Dark appearance, or use the explicit variants available from iOS 16. Forcing a scheme is possible with .preferredColorScheme(.dark), but it is almost always the wrong answer for a user-facing screen.

Dynamic Type is the mechanism by which the user scales text. It works automatically for any text that uses a text style such as .body or .caption. What does not scale automatically is anything you measured yourself.

Image(systemName: "bell")
    .frame(width: 24, height: 24)      // fixed size, does not scale
@ScaledMetric(relativeTo: .body) private var iconSize = 24

Image(systemName: "bell")
    .frame(width: iconSize, height: iconSize)   // scales with the text size

You can also clamp how far the text grows, which is occasionally necessary in a dense layout.

Text("Account")
    .dynamicTypeSize(.small ... .accessibility1)

The layouts most likely to break under large text are the ones built from fixed frames and HStack rows with trailing controls. The fix is usually to allow the text to wrap and to let the row grow.

13. Previews and testing

Previews are the first line of testing, and for layout they are better than a test, because you can look at several sizes at once.

#Preview("Default") {
    InboxView()
}

#Preview("Accessibility XL") {
    InboxView()
        .dynamicTypeSize(.accessibility3)
}

#Preview("Dark") {
    InboxView()
        .preferredColorScheme(.dark)
}

Unit tests for SwiftUI views usually check behaviour rather than pixels. ViewInspector, a third-party library, lets you reach into a view hierarchy and assert on what is there.

import ViewInspector

func testShowsUnreadCount() {
    let view = InboxView(model: .preview(unread: 3))
    let label = view.find(Text.self, where: { $0.content() == "3" })
    XCTAssertNotNil(label)
}

For interactions that matter to the user, a UI test is the right tool. A UI test drives the real application through the accessibility tree.

final class InboxUITests: XCTestCase {
    func testOpeningAMessage() {
        let app = XCUIApplication()
        app.launchArguments = ["-UITestMode"]
        app.launch()

        let cell = app.cells["message-row-1"]
        XCTAssertTrue(cell.waitForExistence(timeout: 5))

        cell.tap()

        XCTAssertTrue(app.navigationBars["Message"].exists)
    }
}

UI tests are slow, so they should be few and they should test journeys rather than implementation details. To make them reliable, give the elements you care about stable accessibility identifiers.

MessageRow(message: message)
    .accessibilityIdentifier("message-row-\(message.id)")

14. Common mistakes

MistakeWhat happensCorrection
NavigationLink(destination:) in new codeThe destination is built eagerly and the path is not inspectableUse NavigationLink(value:) with navigationDestination
A Picker row without tagThe selection does not updateAdd a tag to every option
A GeometryReader in the middle of a stackIt swallows the space and pushes siblings awayMove it to a background or give it an explicit frame
An animation that does not runThe transition is outside withAnimationWrap the state change, or use .animation(_:value:)
Icon-only buttons with no labelVoiceOver announces “button” and nothing elseAdd accessibilityLabel
A hard-coded Color.whiteThe screen is unreadable in dark modeUse a semantic colour
A fixed frame around an iconThe icon does not scale with Dynamic TypeUse @ScaledMetric
A sheet presented from a computed Bool that never resetsThe sheet cannot be reopenedDrive it from a binding you clear

15. Exercise

Build a TasksView that demonstrates the whole toolkit in one screen. It should present a List of tasks with a Section per day, a swipeActions delete action on each row, and a toolbar button that presents a Form in a sheet for adding a task. The form should contain a TextField, a DatePicker, a Toggle and a Picker with a segmented style, all bound to @State in the presenting view. Add a .confirmationDialog to confirm the deletion of a task. Give the row a matchedGeometryEffect transition so that a task selected in the list expands into the detail sheet. Finally, add an accessibilityLabel and an accessibilityHint to every icon-only button, verify the screen in both light and dark appearance with a #Preview, and write a UI test that launches the app, taps the add button, types into the text field and confirms the new task appears in the list.

While you build, check the screen at the largest Dynamic Type size and confirm that nothing is clipped, and turn on VoiceOver to confirm that each control announces something meaningful.

swiftui interfacenavigationlayoutaccessibility

Approach:

The exercise is a coverage exercise rather than a design exercise: every technique in this chapter appears exactly once, so the goal is to make each choice in the smallest correct form rather than to build something elaborate. The structural decision is that the list, the sheet and the confirmation dialog all live in one TasksView, because a sheet needs a binding that the presenting view owns, and a dialog needs a second one. Keeping all three pieces of presentation state in one place makes that ownership obvious and keeps the row view free of presentation concerns.

Steps:

  1. Define a TaskItem model that is Identifiable and Hashable, with an id, a title, a dueDate, an isCompleted flag and a day, plus a TaskDay enum that groups the tasks.
  2. Build TasksView with three pieces of @State: a tasks array, an isPresentingEditor boolean, and a pendingDeletion optional task used by the confirmation dialog.
  3. Present the list inside a NavigationStack, use Section per day with a Section header showing the formatted date, and give each row a swipeActions block whose destructive button sets pendingDeletion rather than deleting immediately.
  4. Attach .confirmationDialog to the list, with a Button("Delete", role: .destructive) that removes the task from the array and a Button("Cancel", role: .cancel).
  5. Present the editor with .sheet(isPresented: $isPresentingEditor) and put a Form inside it with a TextField, a DatePicker, a Toggle and a Picker whose every option carries a tag.
  6. In the editor, dismiss with @Environment(\.dismiss) private var dismiss after saving, and append the new task to the array before dismissing.
  7. Give the toolbar button an accessibilityLabel("Add task"), and give the completion toggle an accessibilityLabel and an accessibilityValue that reflect its state.
  8. Add previews for the default appearance, the dark appearance and the .accessibility3 Dynamic Type size, and give the row an accessibility identifier of the form task-row-<id> so the UI test can find it.
  9. Write the UI test: launch the app, tap the element with the identifier add-task-button, type into the text field with the identifier task-title-field, confirm, and assert that a cell with the identifier for the new task exists.

Answer:

import SwiftUI

enum TaskDay: String, CaseIterable {
    case today = "Today"
    case tomorrow = "Tomorrow"
    case later = "Later"
}

struct TaskItem: Identifiable, Hashable {
    let id: UUID
    var title: String
    var dueDate: Date
    var isCompleted: Bool
    var day: TaskDay

    static let samples: [TaskItem] = [
        TaskItem(
            id: UUID(),
            title: "Write the report",
            dueDate: Date().addingTimeInterval(3600),
            isCompleted: false,
            day: .today
        ),
        TaskItem(
            id: UUID(),
            title: "Review the design",
            dueDate: Date().addingTimeInterval(7200),
            isCompleted: true,
            day: .tomorrow
        )
    ]
}

struct TasksView: View {
    @State private var tasks: [TaskItem] = TaskItem.samples
    @State private var isPresentingEditor = false
    @State private var pendingDeletion: TaskItem?

    var body: some View {
        NavigationStack {
            List {
                ForEach(TaskDay.allCases, id: \.self) { day in
                    Section(day.rawValue) {
                        ForEach(tasks(for: day)) { task in
                            TaskRow(task: task)
                                .swipeActions(edge: .trailing) {
                                    Button("Delete", role: .destructive) {
                                        pendingDeletion = task
                                    }
                                }
                        }
                    }
                }
            }
            .navigationTitle("Tasks")
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        isPresentingEditor = true
                    } label: {
                        Image(systemName: "plus")
                    }
                    .accessibilityLabel("Add task")
                    .accessibilityIdentifier("add-task-button")
                }
            }
            .confirmationDialog(
                "Delete this task?",
                isPresented: Binding(
                    get: { pendingDeletion != nil },
                    set: { if !$0 { pendingDeletion = nil } }
                ),
                titleVisibility: .visible
            ) {
                Button("Delete", role: .destructive) {
                    if let task = pendingDeletion {
                        tasks.removeAll { $0.id == task.id }
                    }
                    pendingDeletion = nil
                }
                Button("Cancel", role: .cancel) {
                    pendingDeletion = nil
                }
            }
            .sheet(isPresented: $isPresentingEditor) {
                TaskEditorView { newTask in
                    tasks.append(newTask)
                }
            }
        }
    }

    private func tasks(for day: TaskDay) -> [TaskItem] {
        tasks.filter { $0.day == day }
    }
}

struct TaskRow: View {
    let task: TaskItem

    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: task.isCompleted ? "checkmark.circle.fill" : "circle")
                .foregroundStyle(task.isCompleted ? .green : .secondary)
                .accessibilityHidden(true)

            Text(task.title)

            Spacer()

            Text(task.dueDate, style: .time)
                .font(.caption)
                .foregroundStyle(.secondary)
        }
        .accessibilityElement(children: .combine)
        .accessibilityIdentifier("task-row-\(task.id.uuidString)")
    }
}

struct TaskEditorView: View {
    @Environment(\.dismiss) private var dismiss

    @State private var title = ""
    @State private var dueDate = Date()
    @State private var isCompleted = false
    @State private var day: TaskDay = .today

    let onSave: (TaskItem) -> Void

    var body: some View {
        NavigationStack {
            Form {
                Section("Details") {
                    TextField("Title", text: $title)
                        .accessibilityIdentifier("task-title-field")
                    DatePicker("Due", selection: $dueDate)
                    Toggle("Completed", isOn: $isCompleted)
                }

                Section("Day") {
                    Picker("Day", selection: $day) {
                        ForEach(TaskDay.allCases, id: \.self) { day in
                            Text(day.rawValue).tag(day)
                        }
                    }
                    .pickerStyle(.segmented)
                }
            }
            .navigationTitle("New task")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel", role: .cancel) { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Save") {
                        onSave(
                            TaskItem(
                                id: UUID(),
                                title: title,
                                dueDate: dueDate,
                                isCompleted: isCompleted,
                                day: day
                            )
                        )
                        dismiss()
                    }
                    .disabled(title.isEmpty)
                }
            }
        }
    }
}

The UI test that goes with it:

final class TasksUITests: XCTestCase {
    func testAddingATask() {
        let app = XCUIApplication()
        app.launch()

        let addButton = app.buttons["add-task-button"]
        XCTAssertTrue(addButton.waitForExistence(timeout: 5))
        addButton.tap()

        let field = app.textFields["task-title-field"]
        XCTAssertTrue(field.waitForExistence(timeout: 5))
        field.tap()
        field.typeText("Write the report")

        app.buttons["Save"].tap()

        XCTAssertTrue(app.staticTexts["Write the report"].waitForExistence(timeout: 5))
    }
}

The three details that make this work are worth calling out. The confirmation dialog is driven by a derived binding, so the boolean is never stored separately from the task being deleted and the two cannot disagree. The picker options each carry a tag, without which the segmented control would render correctly but never update the selection. And the delete button carries the .destructive role, so it is announced by VoiceOver as destructive and rendered in red, which is the difference between a dialog that informs and one that frightens.

More courses

Recommended courses

Found an issue with this content?

Tell us what could be improved.