Presenting Context menu on button tap in swift

Viewed 7832

In iOS context menus can be shown by a long press or a tap. Currently the below code shows a context menu on a long press, how do I present the menu on a tap?

    let interaction = UIContextMenuInteraction(delegate: self)
    tagBtn.addInteraction(interaction)

    func contextMenuInteraction(_ interaction: UIContextMenuInteraction,
      configurationForMenuAtLocation location: CGPoint)
      -> UIContextMenuConfiguration? {

      let favorite = UIAction(title: "Favorite",
        image: UIImage(systemName: "heart.fill")) { _ in
        // Perform action
      }

      let share = UIAction(title: "Share",
        image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
        // Perform action
      }

      let delete = UIAction(title: "Delete",
        image: UIImage(systemName: "trash.fill"),
        attributes: [.destructive]) { action in
         // Perform action
       }

       return UIContextMenuConfiguration(identifier: nil,
         previewProvider: nil) { _ in
         UIMenu(title: "Actions", children: [favorite, share, delete])
       }
    }
1 Answers

UIContextMenuInteraction is intended only for contextual (long-press) menus.

If you want the primary action of the button to display a menu, you can just create a UIMenu and assign it directly to the button.menu property, then set button.showsMenuAsPrimaryAction = true, like this:

let favorite = UIAction(title: "Favorite",
  image: UIImage(systemName: "heart.fill")) { _ in
  // Perform action
}

...

let button = UIButton()
button.showsMenuAsPrimaryAction = true
button.menu = UIMenu(title: "", children: [favorite, ...])
Related