Long press gesture on UICollectionViewCell

前端 未结 8 1073
猫巷女王i
猫巷女王i 2020-11-27 09:46

I was wondering how to add a long press gesture recognizer to a (subclass of) UICollectionView. I read in the documentation that it is added by default, but I can\'t figure

8条回答
  •  情书的邮戳
    2020-11-27 10:25

    The same code @abbood's code for Swift:

    In viewDidLoad:

    let lpgr : UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
    lpgr.minimumPressDuration = 0.5
    lpgr.delegate = self
    lpgr.delaysTouchesBegan = true
    self.collectionView?.addGestureRecognizer(lpgr)
    

    And the function:

    func handleLongPress(gestureRecognizer : UILongPressGestureRecognizer){
    
        if (gestureRecognizer.state != UIGestureRecognizerState.Ended){
            return
        }
    
        let p = gestureRecognizer.locationInView(self.collectionView)
    
        if let indexPath : NSIndexPath = (self.collectionView?.indexPathForItemAtPoint(p))!{
            //do whatever you need to do
        }
    
    }
    

    Do not forget the delegate UIGestureRecognizerDelegate

提交回复
热议问题