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

时间:2020-04-12 14:45:20

标签: ios swift iphone xcode uicollectionviewcell

我试图弄清楚如何对我的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")
        }

但是没有运气。 可能是一种简单的方法,但是我对编程很陌生,在其他帖子或视频上没有任何帮助。

1 个答案:

答案 0 :(得分:-1)

您无需手动处理点击事件。使用此功能获取单元格单击事件。

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

}