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

web*_*ets 22 uigesturerecognizer ios uicollectionviewcell swift

我想弄清楚当我长按单元格时如何打印UICollectionViewCell的indexPath.

我怎么能在Swift中做到这一点?

我已经到处寻找一个如何做到这一点的例子; 在斯威夫特找不到一个.

zta*_*tan 61

首先,你的视图控制器需要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)
    }
Run Code Online (Sandbox Code Playgroud)

处理长按的方法:

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")
        }
    }
Run Code Online (Sandbox Code Playgroud)

此代码基于此答案的Objective-C版本.


chr*_*r0x 10

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")
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我发现的一件事是:

if gestureReconizer.state != UIGestureRecognizerState.Ended {
    return
}
Run Code Online (Sandbox Code Playgroud)

在释放长按之前不会放置图钉,可以,但是我发现

if gestureRecognizer.state == UIGestureRecognizerState.Began { }  
Run Code Online (Sandbox Code Playgroud)

围绕整个功能,可以防止多个引脚放置,同时只要满足定时器延迟,就可以让引脚出现。

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