在 UICollectionView Swift 中获取单击的 UICollectionViewCell 的索引

use*_*734 0 ios uicollectionview swift

如何获取我在 Xcode 中使用 Swift for iOS 制作的 CollectionView 中单击的“Sheep”的索引?

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
}
Run Code Online (Sandbox Code Playgroud)

我通过 Gui 在 TouchDown 上创建了一个发送事件:

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

但我得到的回应来自第二次印刷:

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

可能有某种方法可以确定点击了哪只羊,但我如何获得该信息?

这是它的样子(其他命名然后在帖子中提供): Xcode

rma*_*ddy 5

一种解决方案是根据按钮的位置获取单元格的索引路径。

@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
    }
}
Run Code Online (Sandbox Code Playgroud)