In iOS 9 with Swift , to SHOW ONLY CUSTOMS ITEMS (without cutting by default, pasting, etc.), I managed to work only with the following code.
In the viewDidLoad method:
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(contextMenuHandler)) longPressRecognizer.minimumPressDuration = 0.3 longPressRecognizer.delaysTouchesBegan = true self.collectionView?.addGestureRecognizer(longPressRecognizer)
Override method canBecomeFirstResponder :
override func canBecomeFirstResponder() -> Bool { return true }
Override these two related methods:
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return (action == #selector(send) || action == #selector(delete)) }
Create a gesture handler method:
func contextMenuHandler(gesture: UILongPressGestureRecognizer) { if gesture.state == UIGestureRecognizerState.Began { let indexPath = self.collectionView?.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) if indexPath != nil { self.selectedIndexPath = indexPath! let cell = self.collectionView?.cellForItemAtIndexPath(self.selectedIndexPath) let menu = UIMenuController.sharedMenuController() let sendMenuItem = UIMenuItem(title: "Send", action: #selector(send)) let deleteMenuItem = UIMenuItem(title: "Delete", action: #selector(delete)) menu.setTargetRect(CGRectMake(0, 5, 60, 80), inView: (cell?.contentView)!) menu.menuItems = [sendMenuItem, deleteMenuItem] menu.setMenuVisible(true, animated: true) } } }
And finally, create selection methods:
func send() { print("Send performed!") } func delete() { print("Delete performed!") }
Hope this helps. :)
Greetings.