2017年7月28日 | Leave a comment 问题: ios 如何显示类似文字copy & 粘贴那样的 上下文菜单 解决: class MyViewController : UIViewController{ //MARK: menu func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.becomeFirstResponder() //important!! let menuc = UIMenuController.shared let cell = collectionView.cellForItem(at: indexPath)! menuc.setTargetRect(cell.bounds, in: cell) menuc.menuItems = [UIMenuItem(title:"report", action:#selector(report) )] menuc.update() menuc.setMenuVisible(true, animated: true) } func report(){ ... } override var canBecomeFirstResponder: Bool{ return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let ret = action == #selector(report) return ret } .... } 123456789101112131415161718192021222324252627 class MyViewController : UIViewController{ //MARK: menu func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.becomeFirstResponder() //important!! let menuc = UIMenuController.shared let cell = collectionView.cellForItem(at: indexPath)! menuc.setTargetRect(cell.bounds, in: cell) menuc.menuItems = [UIMenuItem(title:"report", action:#selector(report) )] menuc.update() menuc.setMenuVisible(true, animated: true) } func report(){... } override var canBecomeFirstResponder: Bool{ return true } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { let ret = action == #selector(report) return ret }....} 参考: http://blog.csdn.net/iosworker/article/details/50721731