Start a Project

Context Menus in Swift

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.

UIContextMenuInteraction

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.

Result

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

Exit mobile version