user6023982
user6023982

Reputation: 423

UICollectionViewCell detect tap

I have UICollectionView in ViewController class and I also have a class for UICollectionViewCell.

I have some cells and I need to detect which cell was tapped. How can I detect that?

Upvotes: 0

Views: 2117

Answers (2)

DialDT
DialDT

Reputation: 472

In Swift 5 you can use the didSelectItemAt method:

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath) //will return [0, 0] for the first cell, [0, 1] for the second cell etc...
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100543

Use this delegate method

func collectionView(_ collectionView: UICollectionView, 
         didSelectItemAt indexPath: IndexPath) {

    let tappedCell = collectionView.cellForItem(at:indexPath) as! CustomCellClass
    print(tappedCell.tag)
}

//

collectionView.delegate = self

//

class CustomVC:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { --- }

Upvotes: 2

Related Questions