iOS 14's UIMenu
seems to be able to be presented from any UIBarButtonItem
or UIButton
/ UIControl
, but I how would I present it from a generic UIView
?
Asked
Active
Viewed 2,577 times
7

Joel Fischer
- 6,521
- 5
- 35
- 46
1 Answers
1
Add the interaction:
let interaction = UIContextMenuInteraction(delegate: self)
menuView.addInteraction(interaction)
Add UIContextMenuInteractionDelegate to your controller:
extension YourViewController: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
// Create an action for sharing
let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { action in
// Show system share sheet
}
// Create an action for renaming
let rename = UIAction(title: "Rename", image: UIImage(systemName: "square.and.pencil")) { action in
// Perform renaming
}
// Here we specify the "destructive" attribute to show that it’s destructive in nature
let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { action in
// Perform delete
}
// Create and return a UIMenu with all of the actions as children
return UIMenu(title: "", children: [share, rename, delete])
}
}
}
Now, long-press on the view and see your menu :)

TonyMkenu
- 7,597
- 3
- 27
- 49
-
7I apologize if it wasn't fully clear, I'm looking to present the menu from a generic `UIView` _without_ a long press. – Joel Fischer Jan 07 '21 at 19:35