I implemented methods for context menu with delegate methods like this:
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
configureContextMenu(index: indexPath.row)
}
func configureContextMenu(index: Int) -> UIContextMenuConfiguration {
let context = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { (action) -> UIMenu? in
let edit = UIAction(title: "Edit", image: UIImage(systemName: "square.and.pencil"), identifier: nil, discoverabilityTitle: nil, state: .off) { (_) in
print("edit button clicked")
}
let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), identifier: nil, discoverabilityTitle: nil,attributes: .destructive, state: .off) { (_) in
print("delete button clicked")
}
return UIMenu(title: "Options", image: nil, identifier: nil, options: UIMenu.Options.displayInline, children: [edit,delete])
}
return context
}
It’s working fine and as I wanted. But I am targeting like older audience and I am not sure if they would know that they can hold cells for context menu. So I want to add three dots to right corner and after they tap that it shows same context menu for cell. Is is possible to do this? How can I manually invoke it?
Thanks for help
2
Answers
I believe it is not possible to manually invoke UIContextMenus as their interaction trigger and event management is handled internally as per the docs
The only work around I can think of is to use UIMenu with a UIButton on your collection view cell.
I call it a work around rather than a solution because you will gain with the one tap user experience but you will lose the blurry background and focus of the user interaction that UIContextMenu gives you with collection view and table views.
Nonetheless, here is my implementation of the custom UICollectionViewCell where the button pins to the edges of the cell, however you can size it as you wish. You can check if this is feasible for your use case:
The result is the following on single tap:
For adding context menu to UIButton (working in Xcode 14.0)