[我试图弄清楚如何对我的collectionView进行编程,以检测出点击了哪个单元格,然后我想使用if方法为每个单元格做不同的事情。
执行此操作时:
@objc func tap(_ sender: UITapGestureRecognizer) {
let location = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: location)
if let index = indexPath {
print("Got clicked on index: \(index)!")
}
例如,我的调试器说:当我单击单元格编号3时,单击了索引:[0,3]。我要完成的操作例如是单击单元格3,然后执行某些操作。以及其他所有单元格的不同动作。
例如,我尝试了类似的方法
if indexPath?.section == 3 {
NSLog("Tapped 3")
}
但是没有运气。可能是一种简单的方法,但是我对编程很陌生,在其他帖子或视频上没有任何帮助。
您无需手动处理点击事件。使用此功能获取单元格单击事件。
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
//print(indexPath.row) // this print 2 when you click on 3rd cell(because indexes starting from 0)
if indexPath.row == 2{
//the action you want to do when 3rd cell click
}
// do something you want
}
设置代表
self.collectionView.delegate = self
和实施
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) { }
您不应为此要求使用手势