【问题标题】:didSelectItemAtIndexPath Doesn't Work In Collection View SwiftdidSelectItemAtIndexPath 在集合视图 Swift 中不起作用
【发布时间】:2015-07-28 16:04:52
【问题描述】:
我一直在开发一个新应用程序,它在集合视图中显示 Gif。我还在为我的集合视图中的单元格使用自定义集合视图单元格类。
didSelectItemAtIndexPath 方法虽然不起作用...
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
println("it worked")
// ^this did not print
}
如何更改它以便我可以使用手势识别器获取单击项目的 indexPath?
【问题讨论】:
标签:
ios
objective-c
swift
uicollectionview
uicollectionviewcell
【解决方案1】:
正如@santhu 所说 (https://stackoverflow.com/a/21970378/846780)
didSelectItemAtIndexPath 在没有任何 subView 时被调用
collectionViewCell 响应该触摸。当 textView 响应
那些接触,所以它不会将这些接触转发到它的超级视图,所以
collectionView 不会得到它。
所以,你有一个 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")
}
}