如何在 Swift 中将 UILongPressGestureRecognizer 与 UICollectionViewCell 一起使用?

How do I use UILongPressGestureRecognizer with a UICollectionViewCell in Swift?

我想知道如何在长按单元格时打印 UICollectionViewCell 的 indexPath。

我如何在 Swift 中做到这一点?

我已经到处寻找如何执行此操作的示例;在 Swift.

中找不到

首先,您的视图控制器需要 UIGestureRecognizerDelegate。然后在 viewcontroller 的 viewDidLoad() 方法

中将 UILongPressGestureRecognizer 添加到您的 collectionView
class ViewController: UIViewController, UIGestureRecognizerDelegate {

     override func viewDidLoad() {
         super.viewDidLoad()

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

长按处理方法:

func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
        if gestureReconizer.state != UIGestureRecognizerState.Ended {
            return
        }

        let p = gestureReconizer.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(p)

        if let index = indexPath {
            var cell = self.collectionView.cellForItemAtIndexPath(index)
            // do stuff with your cell, for example print the indexPath
             println(index.row)
        } else {
            println("Could not find index path")
        }
    }

此代码基于 this answer 的 Objective-C 版本。

我发现的一件事是:

if gestureReconizer.state != UIGestureRecognizerState.Ended {
    return
}

在您松开长按之前不会放置图钉,这没问题,但我发现

if gestureRecognizer.state == UIGestureRecognizerState.Began { }  

整个函数将防止多个引脚放置,同时让引脚在定时器延迟满足后立即出现。

此外,上面有一个错字:Reconizer -> Recognizer

ztan answer 转换为 swift 3 语法和次要拼写更新:

func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state != UIGestureRecognizerState.ended {
      return
    }

    let p = gestureRecognizer.location(in: collectionView)
    let indexPath = collectionView.indexPathForItem(at: p)

    if let index = indexPath {
      var cell = collectionView.cellForItem(at: index)
      // do stuff with your cell, for example print the indexPath
      print(index.row)
    } else {
      print("Could not find index path")
    }
}

方法 handleLongProgress 转换为 swift 3 语法工作正常。我只是想补充一点,lpgr的初始化应该改成:

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(gestureReconizer:)))

ztan answer 已转换为 swift 4 语法和次要拼写更新:

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    guard gestureRecognizer.state != .ended else { return }

    let point = gestureRecognizer.location(in: collectionView)

    if let indexPath = collectionView.indexPathForItem(at: point), 
       let cell = collectionView.cellForItem(at: indexPath) {
        // do stuff with your cell, for example print the indexPath
        print(indexPath.row)
    } else {
        print("Could not find index path")
    }
}

Swift 5 & Swift 4 Table 查看单元格

override func viewDidLoad() {
    //MARK:- Add Long Gesture
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
    longPressGesture.minimumPressDuration = 1.0 // 1 second press
    longPressGesture.allowableMovement = 15 // 15 points
    longPressGesture.delegate = self
    self.tablev.addGestureRecognizer(longPressGesture)
}


//MARK:- Long Press Gesture
@objc func longPressed(sender: UILongPressGestureRecognizer)
{

    if sender.state == UIGestureRecognizer.State.ended {
        return
    }
    else if sender.state == UIGestureRecognizer.State.began
    {
        let p = sender.location(in: self.tablev)
        let indexPath = self.tablev.indexPathForRow(at: p)

        if let index = indexPath {
            var cell = self.tablev.cellForRow(at: index)
            // do stuff with your cell, for example print the indexPath
            print(index.row)
            print("longpressed Tag: \(index.row)")
        } else {
            print("Could not find index path")
        }
    }
}

if objc func调用导致错误(Swift 5),

Selector("handleLongPress")替换为#selector(self. handleLongPress) 这是完整的实现。

在你的 viewDidLoad() 中,

        let lpgr = UILongPressGestureRecognizer(target: self, 
                             action:#selector(self.handleLongPress))
        lpgr.minimumPressDuration = 1
        lpgr.delaysTouchesBegan = true
        lpgr.delegate = self
        self._mapView.addGestureRecognizer(lpgr)

并在您的 viewcontroller、

中实施
@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
        if gestureReconizer.state != UIGestureRecognizerState.Ended {
        return
    }

    let p = gestureReconizer.locationInView(self.collectionView)
    let indexPath = self.collectionView.indexPathForItemAtPoint(p)

    if let index = indexPath {
        var cell = self.collectionView.cellForItemAtIndexPath(index)
        // do stuff with your cell, for example print the indexPath
         println(index.row)
    } else {
        println("Could not find index path")
    }

 }