Class

UIMenu

A container for grouping related menu elements in an app menu or contextual menu.

Declaration

class UIMenu : UIMenuElement

Overview

Create UIMenu objects and use them to construct the menus and submenus your app displays. You provide menus for your app when it runs on macOS, and key command elements in those menus also appear in the discoverability HUD on iPad when the user presses the command key. You also use menus to display contextual actions in response to specific interactions with one of your views. Every menu has a title, an optional image, and an optional set of child elements. When the user selects an element from the menu, the system executes the code that you provide.

Listing 1

Adding a menu group containing two menu elements, New and Open, to the File menu

// Ensure that the builder is modifying the menu bar system.
guard builder.system == UIMenuSystem.main else { return }

let newDocument = UIKeyCommand(title: "New",
                               action: #selector(newDocument(_:)),
                               input: "n",
                               modifierFlags: .command)

let openDocument = UIKeyCommand(title: "Open...",
                                action: #selector(openDocument(_:)),
                                input: "o",
                                modifierFlags: .command)

// Use the .displayInline option to avoid displaying the menu as a submenu,
// and to separate it from the other menu elements using a line separator.
let newMenu = UIMenu(title: "", options: .displayInline, children: [newDocument, openDocument])

// Insert menu item at the top of the File menu.
builder.insertChild(newMenu, atStartOfMenu: .file)

To see examples of how to use UIMenu, see Adding Menus and Shortcuts to the Menu Bar and User Interface.

Topics

Creating a Menu Object

struct UIMenu.Identifier

Constants for identifying an app's standard menus.

struct UIMenu.Options

Options for configuring a menu's appearance.

Accessing the Child Elements

var children: [UIMenuElement]

The contents of the menu.

func replacingChildren([UIMenuElement]) -> UIMenu

Creates a new menu with the same configuration as the current menu, but with a new set of child elements.

Getting the Menu Details

var identifier: UIMenu.Identifier

The unique identifier for the current menu.

var options: UIMenu.Options

The configuration options for the current menu.

Relationships

Inherits From

Conforms To

See Also

App Menus

protocol UIMenuBuilder

An interface for adding and removing menus from a menu system.

class UIMenuSystem

An object representing a main or contextual menu system.