UIMenuController with custom item not working with UICollectionview

前端 未结 6 1051
长情又很酷
长情又很酷 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:49

    On iOS 9 with Swift to SHOW ONLY CUSTOM ITEMS (without the default cut, paste and so on), I only managed to make work with the following code.

    On method viewDidLoad:

    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 collection 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 the 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 the selector's methods:

    func send() {
        print("Send performed!")
    }
    
    func delete() {
        print("Delete performed!")
    }
    

    Hope that helps. :)

    Cheers.

提交回复
热议问题