UIMenuController with custom item not working with UICollectionview

前端 未结 6 1011
长情又很酷
长情又很酷 2021-01-13 02:15

I have added custom menu controller when long press on UICollectionViewCell

    [self becomeFirstResponder];
    UIMenuItem *menuItem = [[UIMenuItem alloc] i         


        
6条回答
  •  太阳男子
    2021-01-13 02:42

    You need to trigger delegate functions from custom UICollectionViewCell

    Here is my working sample code for Swift3

    CollectionViewController

    override func viewDidLoad() {
        super.viewDidLoad()
        let editMenuItem = UIMenuItem(title: "Edit", action: NSSelectorFromString("editCollection"))
        let deleteMenuItem = UIMenuItem(title: "Delete", action: NSSelectorFromString("deleteCollection"))
        UIMenuController.shared.menuItems = [editMenuItem, deleteMenuItem]
    
    }
    
    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return action == NSSelectorFromString("editCollection") || action == NSSelectorFromString("deleteCollection")
    }
    
    override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
        print("action:\(action.description)")
        //Custom actions here..
    }
    

    Add following functions to your custom UICollectionViewCell

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return action == NSSelectorFromString("editCollection") || action == NSSelectorFromString("deleteCollection")
    }
    

    To call delegate function from cell (needs to be in your custom UICollectionViewCell)

    func editCollection()
    {
        let collectionView = self.superview as! UICollectionView
        let d:UICollectionViewDelegate = collectionView.delegate!
        d.collectionView!(collectionView, performAction: NSSelectorFromString("editCollection"), forItemAt: collectionView.indexPath(for: self)!, withSender: self)
    }
    func deleteCollection()
    {
        let collectionView = self.superview as! UICollectionView
        let d:UICollectionViewDelegate = collectionView.delegate!
        d.collectionView!(collectionView, performAction: NSSelectorFromString("deleteCollection"), forItemAt: collectionView.indexPath(for: self)!, withSender: self)
    }
    

提交回复
热议问题