Search code examples
iosswiftiphonexcodeuicollectionviewcell

If specific CollectionViewCell is clicked do something


I'm trying to figure out how to program my collectionView to detect what cell is tapped and then I want to do something different for each cell using a if method.

When doing this :

   @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)!")



       }

My debugger says for example : Got clicked on index: [0, 3] when I click on cell number 3. What I want to accomplish is for example if cell 3 is clicked, do something. And different actions for all the other cells.

I tried different methods like this one for example

 if indexPath?.section == 3 {

            NSLog("Tapped 3")
        }

But with no luck. Probably a easy way to do this, but I'm very new to programming and didn't find any help on other posts or videos.


Solution

  • you don’t need to handle click event manually . Use this function for get cell click event.

    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
    
    }