如果单击特定的 CollectionViewCell,请执行某些操作

If specific CollectionViewCell is clicked do something

我正在尝试弄清楚如何对我的 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

}