Long press gesture on UICollectionViewCell

前端 未结 8 955
猫巷女王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:32

    Answers here to add a custom longpress gesture recognizer are correct however according to the documentation here: the parent class of UICollectionView class installs a default long-press gesture recognizer to handle scrolling interactions so you must link your custom tap gesture recognizer to the default recognizer associated with your collection view.

    The following code will avoid your custom gesture recognizer to interfere with the default one:

    UILongPressGestureRecognizer* longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
    
    longPressGesture.minimumPressDuration = .5; //seconds
    longPressGesture.delegate = self;
    
    // Make the default gesture recognizer wait until the custom one fails.
    for (UIGestureRecognizer* aRecognizer in [self.collectionView gestureRecognizers]) {
       if ([aRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
          [aRecognizer requireGestureRecognizerToFail:longPressGesture];
    } 
    
    0 讨论(0)
  • 2020-11-27 10:35

    Swift 5:

    private func setupLongGestureRecognizerOnCollection() {
        let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureRecognizer:)))
        longPressedGesture.minimumPressDuration = 0.5
        longPressedGesture.delegate = self
        longPressedGesture.delaysTouchesBegan = true
        collectionView?.addGestureRecognizer(longPressedGesture)
    }
    
    @objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
        if (gestureRecognizer.state != .began) {
            return
        }
    
        let p = gestureRecognizer.location(in: collectionView)
    
        if let indexPath = collectionView?.indexPathForItem(at: p) {
            print("Long press at item: \(indexPath.row)")
        }
    }
    

    Also don't forget to implement UIGestureRecognizerDelegate and call setupLongGestureRecognizerOnCollection from viewDidLoad or wherever you need to call it.

    0 讨论(0)
提交回复
热议问题