Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 46 ยท Navigation and App Structure

NavigationSplitView and iPad Layouts

Build sidebar-and-detail apps with NavigationSplitView, adapt layouts to size classes and Dynamic Type, and learn how multi-window works on iPad.

A phone shows one screen at a time, so a navigation stack is a natural fit. An iPad, a large iPhone in landscape or a Mac has room for two or three panes side by side: a list of folders, a list of items and the content of the selected item. SwiftUI gives you NavigationSplitView for that layout, and the same code collapses into a stack when space is tight.

This lesson covers the split view, the idea of size classes, how to adapt a layout to the space and the text size you actually get, and how multiple windows work. The SwiftUI code is read-only because the site cannot run an iOS app. The decision logic is shown with runnable Swift stand-ins.

One app, many sizes

iPhone portrait One column at a time, drill down.
iPhone landscape Often a compact height, sometimes wide.
iPad Sidebar, list and detail together.

Design for the space you are given, not for a device name.

1 / 2

A two-column split view

The simplest split view has a sidebar and a detail column. The sidebar is a List whose selection is bound to a piece of state. The detail column reads that state.

Swift
import SwiftUI

struct Folder: Identifiable, Hashable {
    let id: Int
    let name: String
}

struct LibraryView: View {
    let folders = [
        Folder(id: 1, name: "Inbox"),
        Folder(id: 2, name: "Archive"),
        Folder(id: 3, name: "Trash")
    ]
    @State private var selection: Folder?

    var body: some View {
        NavigationSplitView {
            List(folders, selection: $selection) { folder in
                Text(folder.name)
            }
            .navigationTitle("Folders")
        } detail: {
            if let folder = selection {
                Text("Contents of \(folder.name)")
            } else {
                ContentUnavailableView("Pick a folder", systemImage: "folder")
            }
        }
    }
}

Three things matter here:

  • The List(_:selection:) initializer needs a Hashable selection value. Folder? is optional because nothing is selected at first.
  • The detail closure must handle the "nothing selected" case. ContentUnavailableView is the standard placeholder.
  • The view has no idea how wide the screen is. SwiftUI decides how to present the columns.

On a wide screen you see both columns. On a narrow one (an iPhone, or an iPad in a small multitasking window) SwiftUI collapses the split view into a navigation stack: the sidebar is the root screen and choosing a row pushes the detail. You write one view and get both behaviors.

Three columns

Add a middle content column when each category holds a list of items:

Swift
NavigationSplitView {
    List(folders, selection: $selectedFolder) { folder in
        Text(folder.name)
    }
} content: {
    if let folder = selectedFolder {
        List(items(in: folder), selection: $selectedItem) { item in
            Text(item.title)
        }
    }
} detail: {
    if let item = selectedItem {
        ItemDetail(item: item)
    }
}

There are now two selections: selectedFolder and selectedItem. The most common bug is forgetting that picking a new folder should clear the old item. Without that, the detail column keeps showing an item that is not in the visible list. The next TryIt models exactly this data flow.

Swift Two selections that stay consistent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In a real app you would store the selection in a model or in @State, as covered in @State and @Binding. The principle is the same: one source of truth, and a rule that keeps dependent values valid.

Controlling which columns are visible

NavigationSplitView takes a columnVisibility binding of type NavigationSplitViewVisibility, with values such as .all, .doubleColumn, .detailOnly and .automatic. This lets you hide the sidebar for a focused reading mode:

Swift
@State private var visibility = NavigationSplitViewVisibility.all

NavigationSplitView(columnVisibility: $visibility) {
    SidebarView()
} detail: {
    ReaderView()
}

Setting visibility = .detailOnly from a button hides the other columns. SwiftUI also adds its own sidebar toggle in the navigation bar on larger screens, and it adjusts your binding when the user uses it. On a compact screen the visibility is mostly ignored because the view is a stack there.

You can also pick a split style with .navigationSplitViewStyle(.balanced) or .prominentDetail. balanced shrinks the detail to make room for the sidebar, while prominentDetail lets the sidebar overlay it. Which one feels right depends on your content, so try both on a real iPad.

Size classes

How does a view know it has "a lot" of room? SwiftUI reports two coarse size classes, each either compact or regular, one for width and one for height:

Swift
struct AdaptiveGallery: View {
    @Environment(\.horizontalSizeClass) private var horizontalSizeClass
    let photos: [Photo]

    var body: some View {
        let columnCount = horizontalSizeClass == .regular ? 4 : 2
        let columns = Array(repeating: GridItem(.flexible()), count: columnCount)

        ScrollView {
            LazyVGrid(columns: columns) {
                ForEach(photos) { photo in
                    PhotoCell(photo: photo)
                }
            }
        }
    }
}

The environment value is nil on some platforms, so compare with == .regular rather than force-unwrapping it. Typical results are these:

  • iPhone in portrait: compact width, regular height.
  • Most iPhones in landscape: compact width, compact height. Larger models can report a regular width.
  • iPad full screen: regular width and regular height.
  • iPad in a narrow Split View or Slide Over window: compact width.

The last case is why you should never branch on UIDevice.current.userInterfaceIdiom == .pad. An iPad app can be squeezed into a window as narrow as a phone, and SwiftUI will report that through the size class.

Swift Choosing columns from the size class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Adapting without size classes

Size classes are a blunt instrument. Often you want "use this layout if it fits, otherwise that one". ViewThatFits does exactly that: it proposes the available space to each child in order and shows the first that fits.

Swift
ViewThatFits {
    HStack { Avatar(); Name(); FollowButton() }   // try the wide version
    VStack { Avatar(); Name(); FollowButton() }   // fall back to stacked
}

There is also AnyLayout, which lets you switch between HStackLayout and VStackLayout while keeping the identity (and state) of the children, so the change can animate. The layout rules behind all of this are explained in How SwiftUI Layout Works.

Dynamic Type is a layout input

People can raise the text size in Settings, up to the large accessibility sizes. Your layout has to survive that, and the environment tells you when it matters:

Swift
@Environment(\.dynamicTypeSize) private var dynamicTypeSize

var body: some View {
    let layout = dynamicTypeSize.isAccessibilitySize
        ? AnyLayout(VStackLayout(alignment: .leading))
        : AnyLayout(HStackLayout())

    layout {
        Image(systemName: "bell")
        Text("Notifications are turned off for this folder")
    }
}

At normal sizes the icon sits beside the text. At accessibility sizes the text would be squeezed into a thin column, so the row stacks vertically instead. Combine this with .minimumScaleFactor only sparingly: shrinking text defeats the purpose of the setting. Prefer letting text wrap and letting the container scroll.

Test with the largest accessibility size and with a narrow iPad window in Xcode previews or the simulator. Layouts break at those two extremes first.

Several windows

On iPad, and on Mac, a person can open more than one window of your app. A WindowGroup can already create several instances of its root scene. Opening one from code uses the openWindow environment action with a window identifier:

Swift
@main
struct NotesApp: App {
    var body: some Scene {
        WindowGroup {
            LibraryView()
        }
        WindowGroup("Note", id: "note", for: Note.ID.self) { $noteID in
            NoteWindow(noteID: noteID)
        }
    }
}

struct OpenInNewWindowButton: View {
    @Environment(\.openWindow) private var openWindow
    let note: Note

    var body: some View {
        Button("Open in new window") {
            openWindow(id: "note", value: note.id)
        }
    }
}

On iOS, multiple scenes must be enabled in the app's Info.plist (the UIApplicationSceneManifest has a UIApplicationSupportsMultipleScenes key). Each window has its own @State and its own scene phase, which is why shared data belongs in a model object, not in a view. The scene concepts are covered in the next lesson.

Common mistakes

  • Branching on device idiom instead of size class or available space. The app breaks in Split View.
  • Nothing selected in the detail column, with no placeholder. The user sees a blank pane.
  • Stale selection: the selected item is removed from the data but the id remains. Clear or validate it.
  • Hard-coded widths that look right on one iPad and wrong on another. Use flexible grids and ViewThatFits.
  • Putting a NavigationStack around a NavigationSplitView by habit. The split view manages its own navigation. Use a stack inside a column when you need drill-down within that column.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does NavigationSplitView do on a narrow iPhone screen?

    A split view adapts to the available space. When there is not enough room it presents its columns as a navigation stack you drill into.
  2. 2. Which approach is best for choosing a layout in an app that can run in iPad Split View?

    An iPad window can be as narrow as a phone. Size classes and ViewThatFits react to the space your view actually gets.
  3. 3. In a three-column split view, why should choosing a new folder clear the selected item?

    Dependent selections must stay consistent. A stale item id leaves the detail column out of step with the visible list.
  4. 4. What does dynamicTypeSize.isAccessibilitySize tell you?

    It reports the large accessibility text sizes. Layouts often switch from horizontal to vertical there so the text has room to wrap.
  5. 5. Where should data live that several windows of the same app show?

    Each window has its own view state. Shared data belongs in a model (for example an observable object injected into the environment).

Summary

  • NavigationSplitView shows two or three columns on wide screens and collapses into stack navigation on narrow ones.
  • Selection state drives the columns. Handle the empty selection, and keep dependent selections valid.
  • columnVisibility and the split view style control which columns are shown.
  • Read horizontalSizeClass or use ViewThatFits and AnyLayout; do not branch on the device idiom.
  • Dynamic Type sizes are a layout input: stack content at accessibility sizes.
  • Multiple windows each have their own view state, so share data through a model.

Next: The App Protocol, Scenes and Scene Phase