Context Menus in Swift

Updated 5 April 2023


You can simplify interactions with your app using context menus in Swift, Home Screen quick actions, and keyboard shortcuts.

Today, we will learn how we can add context menus in Swift.


An object UIContextMenuInteraction is used to get the user action.

UIContextMenuInteraction tracks the long press gesture and animates the content and displays the contextual menu provided by you.

The UIContextMenuInteraction is inherited from the UIInteraction protocol, which in turn inherits from NSObjectProtocol. We need to conform to the protocol in order to use its functions.

Such as, addInteraction(_:) function is used to add interaction to that particular view.

Please visit here for more references.

Adding Context Menus in Swift

Here is a piece of code that adds a context menu to a view.

We have created a button that when clicked shows the context menus.

The menuItems variable returns an array of elements of type UIAction.

UIAction is responsible for handling the actions performed on the menu items, so we can write our code inside the handler block.

The demoMenu creates UIMenu objects and uses them to construct the menus.

When the user selects an element from the menu, the system executes the code that we provide.

Finally, call the UIMenu as below.


On clicking on the showAction button a pop-over is presented on the screen with the menus as defined in menuItems variable.

Context Menus in Swift

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home