I have set up an UIButton as the rightBarButtonItem in an UIViewController inside an UINavigationController and associated an iOS13 context menu to it.
Long pressing the button shows the context menu as expected.
Is there a way to show the context menu also by tapping on the button (e.g. by adding a target for the .touchUpInside event)?
The button/barButtonItem is set up as follows:
let button = UIButton(type: .system)
button.setImage(UIImage(systemName: "plus"), for: .normal)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
let interaction = UIContextMenuInteraction(delegate: self)
button.addInteraction(interaction)
The context menu is defined as follows:
extension ViewController: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
let importAction = UIAction(title: "Import", image: UIImage(systemName: "folder")) { action in }
let createAction = UIAction(title: "Create", image: UIImage(systemName: "square.and.pencil")) { action in }
return UIMenu(title: "", children: [importAction, createAction])
}
}
}
The context menu is, by design, automatically shown by the system when an appropriate gesture (a force touch or a long press) occurs. You can't manually show it.
From docs:
A context menu interaction object tracks Force Touch gestures on devices that support 3D Touch, and long-press gestures on devices that don't support it.
UIKit manages all menu-related interactions and reports the selected action, if any, back to your app.
UPDATE:
Although it's still not possible to manually show the context menu in iOS 14, it's now possible to show the UIMenu
we create for the context menu as a pull-down menu. Check @Lobo's answer for how to do that on iOS 14.