当我长按一个单元格时,我想知道如何打印UICollectionViewCell的indexPath。
我如何在Swift中做到这一点?
我到处寻找如何做到这一点的例子,但在Swift中找不到。
发布于 2015-03-25 05:11:51
首先,您的视图控制器需要是UIGestureRecognizerDelegate
。然后在视图控制器的viewDidLoad()
方法中向collectionView添加一个UILongPressGestureRecognizer
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版本。
发布于 2016-11-11 20:28:53
ztan答案已转换为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")
}
}
发布于 2016-04-14 03:14:29
我发现的一件事是:
if gestureReconizer.state != UIGestureRecognizerState.Ended {
return
}
在你松开长按键之前不会放大头针,这是可以的,但我发现
if gestureRecognizer.state == UIGestureRecognizerState.Began { }
整个功能将防止多个引脚放置,同时让引脚在满足计时器延迟的情况下立即出现。
还有,上面的一个打字错误:校正器->识别器
https://stackoverflow.com/questions/29241691
复制相似问题