iOS. Apple. Indies. Plus Things.

Create Dividers in UIMenu using UIKit

// Written by Jordan Morgan // Feb 28th, 2022 // Read it in about 1 minutes // RE: Snips

This post is brought to you by Emerge Tools, the best way to build on mobile.

let concatenatedThoughts = """

Welcome to Snips! Here, you'll find a short, fully code complete sample with two parts. The first is the entire code sample which you can copy and paste right into Xcode. The second is a step by step explanation. Enjoy!


The Scenario

Add a divider within a UIMenu using UIKit.

import UIKit

class ContextDividerViewController: UIViewController {
    override func viewDidLoad() {
        // 1
        let topActions = [
            UIAction(title: "Two", image: UIImage(systemName: "2.square"), handler: { (_) in
            UIAction(title: "One", image: UIImage(systemName: "1.square"), handler: { (_) in
        // 2
        let divider = UIMenu(title: "", options: .displayInline, children: topActions)

        let bottomAction = UIAction(title: "Three", image: UIImage(systemName: "3.square"), handler: { (_) in
        // 3
        let items = [bottomAction, divider]
        // 4
        let menu = UIMenu(title: "Divider", children: items)
        let button = UIButton(configuration: .borderedProminent())
        button.setTitle("Open", for: .normal)
        button.showsMenuAsPrimaryAction = true
        button.menu = menu
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

When the context menu is presented, the divider is present:

A context menu showing a divider.

The Breakdown

Step 1
Before a divider can be used, you need one or more items above and below the divider at a minimum. Otherwise, well — there is nothing to divide.

Step 2
This is where the divider comes from. You need a UIMenu using the .displayInline option. Then, just pass in its children.

Step 3
The UIMenu acting as a divider is passed in as submenu to another menu.

Step 4
Finally, it’s assigned to a menu and then presented.

Until next time ✌️


Spot an issue, anything to add?

Reach Out.