skip to content

Navigation Containers and Modals

Stacks driven by a path of values, split views, tabs, sheets, alerts and toolbars. Interviewers ask how state drives navigation, how deep links rebuild a stack and how modals stay fresh.

on this pageshow

explore

questions

22

In SwiftUI, how do you present a sheet from a Boolean state value, and how does the sheet's own view close it?

level: juniorimportance: must knowfreq 78%

answer

  1. presentation is state you own
  2. a binding SwiftUI can write back
  3. sheet(isPresented:onDismiss:content:)
  4. dismiss read inside the sheet's view

basics

~20 s

Attach sheet(isPresented:) to a view and bind it to an @State Bool; setting it to true presents the content closure. Inside the sheet's own view, read @Environment(.dismiss) and call dismiss(), or set the Bool back to false.

solid answer

~40 s

`sheet(isPresented:onDismiss:content:)` takes a `Binding<Bool>`: the presenting view owns `@State private var isAddingContact = false`, a button sets it to `true`, and SwiftUI presents whatever the `content` closure returns. Because it holds a binding, SwiftUI writes `false` back when the person drags the sheet down, so the state stays in step with the screen. To close the sheet from inside, the sheet's own view declares `@Environment(\.dismiss) private var dismiss` and calls `dismiss()`; the presenter can also set the Bool to `false`. `onDismiss` is the closure SwiftUI runs when the sheet goes away, useful for follow-up work such as reloading a list. The classic slip is reading `dismiss` in the presenting view and calling it from the content closure: that action belongs to the presenter's environment, so the sheet stays up.

code

swift · 28 lines
swift
import SwiftUI

struct ContactsScreen: View {
    @State private var isAddingContact = false

    var body: some View {
        Button("Add Contact") {
            isAddingContact = true
        }
        .sheet(isPresented: $isAddingContact, onDismiss: {
            print("Add-contact sheet closed")
        }) {
            NewContactView()
        }
    }
}

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

    var body: some View {
        VStack(spacing: 16) {
            Text("New Contact")
            Button("Done") { dismiss() }
        }
        .padding()
    }
}

go deeper

for a junior

Recall the shape: an @State Bool, the sheet(isPresented:) modifier with a content closure, and dismiss read from the environment inside the sheet's own view.

for a middle

Explain why the binding matters: SwiftUI writes false back on a swipe, and the dismiss action targets the environment it was read in, which is why it must live inside the sheet's view.

for a senior

Show you keep presentation state honest in real screens: one source of truth per presentation, onDismiss for follow-up work, and a dedicated content view so dismiss always reaches the sheet.

for a principal

Frame presentation as declarative state: the reviewer's question is who owns each presentation flag, and whether the screen's modal state can be read and reset from one place.

## Presentation is a value you own In SwiftUI you never call a "present" method on a view. A **modal presentation** (a sheet, a full-screen cover, a popover, an alert) is declared with a **view modifier**, and the modifier watches a piece of state that you own. Apple's documentation on modal presentations puts it this way: you provide a `Binding` to the condition, SwiftUI detects when the condition changes and makes the presentation for you, and because it holds a binding it can reset the underlying value when the person dismisses the presentation. Three consequences are worth saying out loud in an interview: - **The source of truth is your state**, usually a private `@State` Bool on the presenting view. - **SwiftUI writes back through the binding**, so after a swipe-down the Bool is `false` again without any code of yours. - **The modifier, not the button, owns the presentation.** The button only flips a value; the `sheet` modifier decides what appears. ## Presenting with sheet(isPresented:onDismiss:content:) The modifier has been in SwiftUI since iOS 13. Its declaration is `sheet(isPresented: Binding<Bool>, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content)`. A contacts screen that opens an "add contact" form looks like this: ```swift struct ContactsScreen: View { @State private var isAddingContact = false var body: some View { Button("Add Contact") { isAddingContact = true } .sheet(isPresented: $isAddingContact) { NewContactView() } } } ``` Two habits keep this clean: - Keep the `content` closure a short call into a **dedicated view type** such as `NewContactView`. That view can then declare its own state and read its own environment values. - Use `onDismiss` for **follow-up work** after the sheet goes away (reloading a list, clearing a selection), not for building content. ## Three ways the sheet closes 1. **The person drags it down.** This is the interactive dismissal; SwiftUI sets the bound Bool to `false`. 2. **Code inside the sheet calls the `dismiss` action** from the environment. 3. **The presenter sets the Bool to `false`** itself, for example after a timer or a network response. | Way to close | Where the code lives | What it needs | |---|---|---| | Swipe down | nowhere, the system handles it | nothing | | `dismiss()` | a view inside the sheet | `@Environment(\.dismiss)` read in that view | | `isAddingContact = false` | the presenting view | access to the state or a binding to it | Whichever path runs, the end state is the same: the Bool is `false` and the sheet is gone. ## The dismiss action belongs to where you read it `@Environment(\.dismiss)` hands you a `DismissAction` (iOS 15 and later). You call it like a function because the type defines `callAsFunction()`. What it does depends on **where you read it**: inside a view that a sheet presents, it dismisses that sheet; inside a view pushed onto a navigation stack, it pops that view (covered with stack-based routing). Apple's documentation calls out the mistake directly. If the presenting view declares `dismiss` and calls it from the sheet's `content` closure, the sheet **fails to dismiss**, because the action applies to the environment where it was declared, which is the presenter's. In macOS and iPadOS, if that presenter is the root view of a window, the action can close the window instead. The fix is structural: move the button into a separate view type that is the sheet's content, and read `dismiss` there. Two related environment values: - `isPresented` (iOS 15) tells a view whether it is currently presented. The documentation notes that `dismiss` has no effect on a view that is not presented. - `presentationMode` is the iOS 13 predecessor. The SDK marks it for deprecation with the message "Use isPresented or dismiss", so new code should not reach for it. ## What to know next - **Landscape iPhone.** Apple's sheet documentation says that in vertically compact environments, such as an iPhone in landscape, a sheet adapts to appear as a full-screen cover. `presentationCompactAdaptation(_:)` (iOS 16.4) overrides that. - **Data for the sheet.** When the sheet needs to know *which* contact to show, prefer `sheet(item:onDismiss:content:)`, which hands the item to the closure instead of reading a second piece of state. - **Height.** A plain sheet rests at full height; `presentationDetents(_:)` (iOS 16) lets it rest lower. A junior answer that names the binding, shows `@State` driving it, and puts `dismiss` inside the sheet's own view covers what an interviewer is listening for.

  • Why does calling dismiss() declared in the presenting view fail to close the sheet?
    A `DismissAction` acts on the environment where it is read. Declared in the presenter, it targets the presenter, not the sheet, so Apple's documentation says the sheet fails to dismiss; on iPadOS or macOS it may even close the presenter's window if that view is the window root. Read `dismiss` in a separate view type that is the sheet's content, or set the presentation Bool to `false`.
  • How can a view find out whether it is currently being shown as a presentation?
    Read `@Environment(\.isPresented)`, available from iOS 15. It is `true` while the view is presented. The documentation also notes that calling `dismiss` on a view that is not presented has no effect, so `isPresented` is the way to decide, for example, whether to show a Close button at all.
  • What does a sheet look like on an iPhone in landscape, and can you change it?
    Apple's sheet documentation says that in a vertically compact environment, such as iPhone landscape, a sheet adapts to appear as a full-screen cover. From iOS 16.4 you can apply `presentationCompactAdaptation(_:)` inside the sheet's content to request a different adaptation, for example `.none` to keep the sheet appearance.

  • You present a sheet by building the view and calling a present method on it.
  • After a swipe-down the Bool stays true until your code resets it.
  • Reading dismiss in the presenter and calling it inside the sheet closure closes the sheet.
  • onDismiss is where you build the content the sheet shows.
  • New code should use presentationMode.wrappedValue.dismiss() to close a sheet.
open as a page

In SwiftUI, how do you build a tab bar with TabView and the Tab type, and what did Tab replace?

level: juniorimportance: must knowfreq 65%

basics

~20 s

Place one Tab per section inside a TabView: each Tab takes a title, an SF Symbol name and a content closure, and badge(:) adds a count. Tab arrived in iOS 18; earlier code used tabItem(:) and tag(_:) on child views.

open as a page

In SwiftUI, how do you put a compose button and a sort menu into a screen's navigation bar with toolbar and ToolbarItem placements?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Apply .toolbar to the screen's content inside a NavigationStack and wrap each control in a ToolbarItem or ToolbarItemGroup with a placement such as .topBarTrailing, .topBarLeading, .principal or .bottomBar; SwiftUI then lays the items out in the bars.

open as a page

In SwiftUI, how do you build a three-column NavigationSplitView for a mail app where each column's selection drives the next?

level: middleimportance: must knowfreq 55%

basics

~20 s

Use NavigationSplitView's sidebar, content and detail closures; bind the mailbox List and the message List to optional @State selections, and let each later column read the earlier selection, showing a placeholder while it is nil.

open as a page

With SwiftUI's NavigationStack, when do you bind a typed array versus a NavigationPath, and how do you push, pop and pop to root?

level: middleimportance: must knowfreq 68%

basics

~20 s

Bind a typed array when every pushed value shares one route type, so code can read it; bind a NavigationPath when one stack mixes types. Push with append, pop with removeLast, and pop to root by emptying the path.

open as a page

In SwiftUI, how do you use the searchable modifier to filter a list of notes, and what decides where the search field appears?

level: middleimportance: must knowfreq 65%

basics

~20 s

Keep the query in your own @State, bind it with .searchable(text:) on a view inside a NavigationStack or NavigationSplitView, and filter the rows from that text; platform, modifier position and the placement request decide where the field appears.

open as a page

A SwiftUI contacts list sets selectedContact and then a Bool to open an edit sheet, but the sheet sometimes shows no contact or the previous one; why, and how do you fix it?

level: seniorimportance: must knowfreq 62%

basics

~20 s

The Bool and selectedContact are two separate states describing one fact, so the sheet's closure can read a value from before the update. Present with sheet(item: $selectedContact) instead: the sheet appears when the contact is non-nil and receives that contact.

open as a page

How do you build a paged onboarding flow with SwiftUI's TabView page style, and how does a Next button move to the next page?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Apply .tabViewStyle(.page) to a TabView of pages: people swipe horizontally and dots show the position. Bind TabView(selection:) to the page value; a Next button changes that value, wrapped in withAnimation so the page slides.

open as a page

In SwiftUI, how do you show an alert or confirmation dialog that carries data, such as the contact being deleted or a failed save?

level: middleimportance: should knowfreq 55%

basics

~20 s

Pass the data through presenting: on confirmationDialog or alert: it appears only when the Bool is true and the data is non-nil, and hands that data to the actions. The iOS 27 SDK adds item: and error: forms driven by one optional.

open as a page

In SwiftUI, when do you choose fullScreenCover or popover over a sheet, and how does a popover behave on iPhone?

level: middleimportance: should knowfreq 35%

basics

~20 s

Use fullScreenCover for a takeover task and give it a Close button; use popover for small content anchored to a control on iPad or Mac. On iPhone a popover adapts into a sheet unless presentationCompactAdaptation says otherwise.

open as a page

In SwiftUI, how do presentationDetents and presentationDragIndicator make a sheet rest at half height, and where do you apply them?

level: middleimportance: should knowfreq 50%

basics

~10 s

Apply presentationDetents([.medium, .large]) to the view inside the sheet's content closure; the sheet then rests at those heights and people drag between them. presentationDragIndicator(.visible) shows the grabber. Both need iOS 16.

open as a page

In SwiftUI, what does TabView's sidebarAdaptable style do on iPad and iPhone, and when would you choose it over NavigationSplitView?

level: middleimportance: should knowfreq 30%

basics

~20 s

The sidebarAdaptable TabView style, from iOS 18, lets iPad people switch between a tab bar and a sidebar that shows TabSection groups, while iPhone keeps a tab bar. Choose it for top-level destinations; choose NavigationSplitView for list-to-detail drilling.

open as a page

In SwiftUI, how do you switch tabs programmatically with TabView(selection:) and Tab values, and what does the search tab role add?

level: middleimportance: should knowfreq 50%

basics

~20 s

Bind TabView(selection:) to @State and give every Tab a unique value of that Hashable type; assigning the state switches tabs. The iOS 18 search role adds Search's default title and symbol and pins the tab at the trailing edge.

open as a page

In SwiftUI, when do you use a Menu instead of the contextMenu modifier, and how do you build a sort Picker inside a toolbar Menu?

level: middleimportance: should knowfreq 45%

basics

~20 s

Menu is a visible control that opens on tap, so it suits a toolbar sort button; contextMenu attaches hidden shortcuts to content, revealed by touch and hold. A Picker inside a Menu shows inline options with a checkmark on the selection.

open as a page

In SwiftUI, how do you stop a contact-edit sheet from being swiped away with unsaved changes while Cancel and Save still close it?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Apply interactiveDismissDisabled(draft != original) inside the sheet so the swipe is blocked only while there are unsaved changes. Programmatic dismissal still works, so Save and Cancel call dismiss(), and Cancel can confirm discarding first.

open as a page

On iPhone a SwiftUI NavigationSplitView collapses into one stack; how does SwiftUI pick what shows there, and how do columnVisibility and preferredCompactColumn behave?

level: seniorimportance: should knowfreq 45%

basics

~10 s

In narrow widths NavigationSplitView collapses into one stack and shows the last column with useful content, driven by selection. columnVisibility is ignored while collapsed; preferredCompactColumn (iOS 17) chooses which column sits on top.

open as a page

How do you restore a SwiftUI NavigationStack's path after relaunch, and why can NavigationPath's codable property return nil?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Make every route value Codable, encode the path when the scene goes to the background, and decode it at launch. NavigationPath's codable returns nil when any element in the path isn't Codable, because the path itself only requires Hashable.

open as a page

In a SwiftUI notes app, a view reads @Environment(\.isSearching) to show results, but the value never turns true and dismissSearch does nothing; why, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

isSearching and dismissSearch are only set for views beneath the searchable modifier; reading them in the view that applies .searchable sees the outer environment. Move the reads into a child view wrapped by .searchable, and pass dismissSearch into sheets.

open as a page

In a modular SwiftUI app, how do feature modules register their screens on a shared NavigationStack, and does that push you toward a NavigationPath or a typed array of one app-wide route enum?

level: principalimportance: should knowfreq 30%

basics

~20 s

Each feature exports a Hashable route type and a modifier that calls navigationDestination(for:) for it; the app target applies those modifiers at each stack's root. A NavigationPath then holds every feature's routes without a shared enum but is opaque; one app-wide enum keeps the path typed but must know every feature.

open as a page

On iOS 27, how does SwiftUI choose which toolbar items move into the overflow menu, and how do visibilityPriority and ToolbarOverflowMenu change that?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

When a toolbar lacks space, SwiftUI moves items into an overflow menu. On iOS 27, visibilityPriority(_:) on a toolbar item makes lower-priority items move first, and ToolbarOverflowMenu puts actions in that menu regardless of space.

open as a page