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.
1 2 3 4 5 6 7 8 9 10 |
var menuItems: [UIAction] { return [ UIAction(title: "Standard item", image: UIImage(systemName: "sun.max"), handler: { (_) in }), UIAction(title: "Disabled item", image: UIImage(systemName: "moon"), attributes: .disabled, handler: { (_) in }), UIAction(title: "Delete..", image: UIImage(systemName: "trash"), attributes: .destructive, handler: { (_) in }) ] } |
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.
1 2 3 |
var demoMenu: UIMenu { return UIMenu(title: "My menu", image: nil, identifier: nil, options: [], children: menuItems) } |
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.
1 2 3 4 5 6 7 8 |
@IBAction func showAction(_ sender: Any) { configureButtonMenu() } func configureButtonMenu() { showBtn.menu = demoMenu showBtn.showsMenuAsPrimaryAction = true } |
Result
On clicking on the showAction button a pop-over is presented on the screen with the menus as defined in menuItems variable.