user1469734
user1469734

Reputation: 801

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

Upvotes: 0

Views: 2732

Answers (2)

Durdu
Durdu

Reputation: 4859

You can set and check the button property "tag" (if you have the outlet set to the controller)

Here is another easy solution:

Have a new property for the callback.

    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
        }
        cell.callBack = { [weak self] collectionViewCell in 
               let indexPath = collectionView.indexPath(for: collectionViewCell)
               self?.doStuffFor(indexPath)
        } 
        return cell
    }

and on the cell you can have the ibaction

    cell class
    //...

    var callBack : ((UICollectionViewCell?)->Void)?
    //...

    @IBAction func action(_ sender: UIButton) {
         self.callBack?(self)
    }

Upvotes: 2

rmaddy
rmaddy

Reputation: 318944

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
    }
}

Upvotes: 6

Related Questions