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])
}
}
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.
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.
A context menu view allows you to present a situationally specific menu that enables taking actions relevant to the current task.
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, ...])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With