Create context menu for UIButton in Swift UIKit

Chanakya Hirpara
2 min readJan 20, 2022

--

Sometimes there is situation when you have to display some options to choose when clicking on UIButton like tooltip. Here comes iOS default functionality to help us after iOS 14.

Prerequisite

Prior knowledge of Swift and UIKit.

We have to assign menu items to the button so that upon clicking UIButton we can see menu populated.

let editAction = UIAction(title: "Edit",image: UIImage(named: "editIcon")) { action in}let deleteAction = UIAction(title: "Delete",image: UIImage(named: "trashIcon"), attributes: UIMenuElement.Attributes.destructive) { action in}button.menu = UIMenu(children: [editAction, deleteAction])button.showsMenuAsPrimaryAction = true
  1. Here we are assigning menu items to the UIButton by the“menu” property. But UIMenu class requires the menu items to be populated.
  2. So we create UIAction object with “Title”, “Image”, “Click Handler Closure” so that menu items will be populated using “Title” and “Image” passed to it.
  3. The attributes here we used for deleteAction is “UIMenuElement.Attributes.destructive” that’s why it is considered as the menu-item that will remove something and make it red!
  4. At last we have to tell UIButton that its gonna populate menu that is passed to it when its tapped by making “showsMenuAsPrimaryAction” property true.
  5. Build and tap on UIButton and wow you can see menu!
  6. Hope you learned something new. If you like my post please do clap and share it.

--

--

No responses yet