skip to content

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%

answer

  1. visible control vs hidden gesture
  2. touch and hold reveals it
  3. a Picker in a menu shows checkmarks
  4. primaryAction moves the menu to long press

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.

solid answer

~40 s

A `Menu` has a label people can see, such as a sort icon in the toolbar, and tapping it opens its content: `Button`, `Toggle`, `Picker`, a nested `Menu` for a submenu, `Section` and `Divider`. With `primaryAction:`, a tap runs that action and the menu opens on a long press instead. `contextMenu(menuItems:)` adds a menu to an existing view that appears on touch and hold, so it carries shortcuts for that item, like Pin or Delete on a note, never the only path to an action. `contextMenu(menuItems:preview:)` (iOS 16) shows a custom preview beside it. For sorting I put a `Picker` bound to the sort key inside the toolbar `Menu`; by default it renders inline with a checkmark on the current choice, and `.pickerStyle(.menu)` turns it into a submenu.

code

swift · 16 lines
swift
struct ComposeButton: View {
    let onNewNote: () -> Void
    let onNewFromTemplate: () -> Void
    let onNewChecklist: () -> Void

    var body: some View {
        Menu {
            Button("New from Template", systemImage: "doc.on.doc", action: onNewFromTemplate)
            Button("New Checklist", systemImage: "checklist", action: onNewChecklist)
        } label: {
            Label("New Note", systemImage: "square.and.pencil")
        } primaryAction: {
            onNewNote()
        }
    }
}

go deeper

for a junior

Recall that Menu is a visible control opened by a tap, while contextMenu is attached to content and opened by touch and hold.

for a middle

Explain what each control becomes inside a menu, the inline Picker with checkmarks, primaryAction's split of tap and long press, and the preview: variant from iOS 16.

for a senior

Show product judgment: never hide the only path to an action in a context menu, fix reordering with menuOrder(.fixed), and keep destructive items marked with a role.

for a principal

Frame menu use as a design-system rule: which actions are visible, which are shortcuts, and how one declaration adapts across iPhone, iPad and Mac.

## Two menus, two jobs SwiftUI gives you two different ways to show a list of commands, and the choice is about **discoverability**. - **`Menu`** is a **control**. It has a label that is always on screen, such as a button in the toolbar, and tapping that label presents the menu's items. People can find it by looking. - **`contextMenu(menuItems:)`** is a **view modifier** that attaches a menu to content you already show, such as a row or an image. On iPhone and iPad it appears when someone **touches and holds** the content, and the system dismisses it when they pick an item or tap outside it. Nothing on screen advertises it. Apple's "Menus and commands" overview frames them the same way: menus give "space-efficient, context-dependent access to commands", and context menus are ones "people reveal near their current task". Because a context menu is hidden, it should repeat actions that are reachable elsewhere, for example by swipe or on the detail screen, not be their only home. ## Building a Menu ```swift Menu("Sort", systemImage: "arrow.up.arrow.down") { Picker("Sort by", selection: $sortKey) { Text("Date Edited").tag(SortKey.edited) Text("Title").tag(SortKey.title) } Toggle("Pinned First", isOn: $pinnedFirst) Divider() Button("Delete All", systemImage: "trash", role: .destructive) { confirmDeleteAll() } } ``` What each piece does inside a menu: - **`Button`** becomes an actionable item; `role: .destructive` tints it red. - **`Toggle`** shows a checkmark for its on state. - **`Picker`** shows its options **inline** by default, with a checkmark on the current selection, so only one can be active. `.pickerStyle(.menu)` makes it a **submenu** instead, and `.pickerStyle(.palette)` gives a compact row of symbols. - A **nested `Menu`** becomes a submenu; **`Section`** groups items under a header while keeping them visible; **`Divider`** draws a separator. - A `Button` whose label holds **two `Text` views** shows a title and a subtitle. Two behaviours surprise people on iOS: 1. **Ordering.** By default the system rearranges items so the first ones sit closest to the point of interaction, which can flip a menu opened near the bottom of the screen. `menuOrder(.fixed)` (iOS 16) keeps your declared order. 2. **Dismissal.** A menu closes as soon as an item is chosen. `menuActionDismissBehavior(.disabled)` on an item, such as "Increase font size", lets people tap it repeatedly. ## A menu with a primary action `Menu(content:label:primaryAction:)` (iOS 15) splits the gestures: a **tap runs `primaryAction`**, and the menu opens on a **secondary gesture such as a long press**. A compose button that creates a blank note on tap and offers "New from Template" on long press is the classic use. ## Building a context menu ```swift Text(note.title) .contextMenu { Button("Pin", systemImage: "pin", action: pin) Button("Delete", systemImage: "trash", role: .destructive, action: delete) } preview: { NotePreview(note: note) } ``` - **`contextMenu(menuItems:)`** (iOS 13) uses the lifted content itself as the preview. Returning nothing from the closure turns the menu off. - **`contextMenu(menuItems:preview:)`** (iOS 16) shows your own preview view, sized to its content, next to the menu; useful for showing a note's first lines while the row shows only its title. macOS shows the menu but not the preview. - To change the lifted shape, such as its corner radius, apply `contentShape(_:_:eoFill:)` with the `.contextMenuPreview` kind. - For a `List` or `Table` with selection, `contextMenu(forSelectionType:menu:primaryAction:)` hands you the selected identifiers, so one menu acts on several rows; selection itself belongs with list rows and editing. ## Choosing between them | Question | `Menu` | `contextMenu` | |---|---|---| | Visible on screen? | Yes, its label | No, revealed by touch and hold | | Acts on | The screen or a whole collection | The item it is attached to | | Typical place | Toolbar: sort, filter, "more" | A row, a card, an image | | Custom preview | Not applicable | `preview:` closure, iOS 16 | A quick review checklist for a pull request that adds menus: - Every context-menu action is also reachable from a visible control. - Destructive items carry `role: .destructive`, and a confirmation follows where the action cannot be undone. - A sort or filter choice is a `Picker` bound to state, not a row of buttons that each set a value and lose the checkmark. - Ordering is fixed with `menuOrder(.fixed)` where the order carries meaning. On iPad and Mac, menu-bar commands built with `commands(content:)` are a third kind of menu that belongs with app scenes, not with in-screen menus.

  • Why should an action never live only in a context menu?
    A context menu has no visible affordance: it appears only when someone touches and holds the content. People who never try that gesture may never find it. Put the action somewhere visible as well, such as the detail screen, a toolbar menu or a swipe action, and treat the context menu as a shortcut.
  • Your sort menu opened near the bottom of the screen shows its items in reverse order. Why, and what fixes it?
    On iOS and iPadOS the system reorders menu items by default so the first items sit nearest the point of interaction, so a menu that opens upward can appear flipped. Apply `menuOrder(.fixed)` to the `Menu`, available since iOS 16, to keep the order you declared.

A Menu is a labelled drawer in the toolbar: anyone can see it and pull it open. A context menu is the set of options a shop assistant offers only when you hold up a specific item and ask; useful, but nobody knows it is there unless told.

  • A context menu is a fine only home for an important action
  • A Picker inside a Menu always opens as a separate submenu
  • primaryAction makes the menu open on tap and run the action on long press
  • contextMenu with preview works on iOS 13
  • Menu items always appear in the declared order on iOS