Long press gesture on UICollectionViewCell

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

提交回复
热议问题