didSelectItemAtIndexPath 在集合视图中不起作用 Swift
didSelectItemAtIndexPath Doesn't Work In Collection View Swift
我一直在开发一个新应用程序,它在集合视图中显示 Gif。我还为我的集合视图中的单元格使用自定义集合视图单元格 class。
虽然方法didSelectItemAtIndexPath
不起作用...
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
println("it worked")
// ^this did not print
}
我该如何更改它以便我可以使用手势识别器获取被单击项目的 indexPath?
如@santhu 所说 ()
didSelectItemAtIndexPath is called when none of the subView of
collectionViewCell respond to that touch. As the textView respond to
those touches, so it won't forward those touches to its superView, so
collectionView won't get it.
所以,你有一个 UILongPressGestureRecognizer
并且它避免了 didSelectItemAtIndexPath
调用。
使用 UILongPressGestureRecognizer
方法,您需要处理 handleLongPress
委托方法。基本上你需要得到 gestureReconizer.locationInView
并知道位于此时的 indexPath (gestureReconizer.locationInView
).
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")
}
}
我一直在开发一个新应用程序,它在集合视图中显示 Gif。我还为我的集合视图中的单元格使用自定义集合视图单元格 class。
虽然方法didSelectItemAtIndexPath
不起作用...
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
println("it worked")
// ^this did not print
}
我该如何更改它以便我可以使用手势识别器获取被单击项目的 indexPath?
如@santhu 所说 ()
didSelectItemAtIndexPath is called when none of the subView of collectionViewCell respond to that touch. As the textView respond to those touches, so it won't forward those touches to its superView, so collectionView won't get it.
所以,你有一个 UILongPressGestureRecognizer
并且它避免了 didSelectItemAtIndexPath
调用。
使用 UILongPressGestureRecognizer
方法,您需要处理 handleLongPress
委托方法。基本上你需要得到 gestureReconizer.locationInView
并知道位于此时的 indexPath (gestureReconizer.locationInView
).
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")
}
}