user1469734 user1469734 - 6 months ago 62
Swift Question

Get index of clicked UICollectionViewCell in UICollectionView Swift

How do I get the index of the "Sheep" I clicked on in a CollectionView made in Xcode with Swift for iOS?

class SheepsOverviewVC:
UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "class", for: indexPath) as! ClassesCollectionCell
if(sheeps.count > 0) {
cell.ClassImageView.image = UIImage(named: sheeps[indexPath.row] as! String)
cell.SheepName.text = names[indexPath.row] as? String
}
return cell
}


I created a Sent Event on the TouchDown via the Gui:

@IBAction func clickingSheep(_ sender: UIButton) {
print("This will show info about the Sheep")
print(sender)
}


But the response I get is from the second print:

<UIButton: 0x7f9a63021d20; frame = (50 50; 136 169); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x60800003d260>>


Probably there is some way to figure out which Sheep was clicked, but how do I get that information?

This is how it looks like (other namings then provided in the post):
Xcode

Answer Source

One solution is to get the index path of the cell based on the button's location.

@IBAction func clickingSheep(_ sender: UIButton) {
    let hitPoint = sender.convert(CGPoint.zero, to: collectionView)
    if let indexPath = collectionView.indexPathForItem(at: hitPoint) {
        // use indexPath to get needed data
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download