如何显示UICollectionViewCell的MenuController?

时间:2016-01-27 10:31:22

标签: ios swift uicollectionview uimenucontroller uipasteboard

我怎样才能重现像iPhone上的消息的复制粘贴功能,如果你长按消息,消息单元格会变灰并且弹出一个带有“复制”的弹出窗口。如何在我的UICollectionViewCells上显示相同的菜单?

1 个答案:

答案 0 :(得分:1)

事实证明,他已经内置了功能,就像实现三个collectionView:委托方法一样简单。我创建了一个协议CopyableCell,其中包含一个名为copyableProperty的属性,一个单元格要复制到剪贴板的字符串,我可以复制的单元格必须跟随。从那时起它很简单:

  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
    }
  }