Search code examples
iosswiftuicollectionviewuimenucontrolleruipasteboard

How to show MenuController of UICollectionViewCell?


How could I reproduce the copy paste function of say, Messages on iPhone, where if you long press on a message, the message cell goes gray-ish and a little pop-up with "copy" shows up. How can I show that same menu on my UICollectionViewCells?


Solution

  • As it turns out he functionality is already built in and is as simple as implementing three collectionView: delegate methods. I created a protocol CopyableCell with a property called copyableProperty, the string that a cell wants to copy to the clipboard, that the cells that I can copy must follow. It was straightforward from then on:

      func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        if let _ = collectionView.cellForItemAtIndexPath(indexPath) as? CopyableCell {
          return true
        }
        return false
      }
      func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        if action.description == "copy:" {
          return true
        }
    
        return false
      }
    
      func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
        //No more checking is needed here since we only allow for copying
        if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CopyableCell {
          UIPasteboard.generalPasteboard().string = cell.copyableProperty
        }
      }