Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presenting Context menu on button tap in swift

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])
       }
    }
like image 630
Ibrahim99 Avatar asked Jan 20 '21 10:01

Ibrahim99


People also ask

How do you show a menu when a button is pressed Swift?

As of iOS 14 and SwiftUI 2 we can now add a pop out menu to any button in our app. We can implement this by using the new Menu keyword. Menus in some way are going to replace the current action sheets used in iOS apps.

How do I display context menu?

The context menu (right-hand mouse button or SHIFT+F10 ) allows you to display a context-sensitive menu. The context is defined by the position of the mouse pointer when the user requests the menu. A context menu allows the user to choose functions that are relevant to the current context.

What is context menu in Swift?

A context menu view allows you to present a situationally specific menu that enables taking actions relevant to the current task.


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, ...])
like image 53
Nick Lockwood Avatar answered Oct 17 '22 02:10

Nick Lockwood