簡體   English   中英

獲取UICollectionView Swift中單擊的UICollectionViewCell的索引

[英]Get index of clicked UICollectionViewCell in UICollectionView Swift

如何獲取在iOS的Swift的Xcode中創建的CollectionView中單擊的“綿羊”的索引?

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
}

我通過Gui在TouchDown上創建了一個已發送事件:

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

但是我得到的答復來自第二張印刷品:

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

可能有某種方法可以確定單擊了哪只羊,但是如何獲得該信息?

這是這樣的樣子(帖子中隨后提供了其他名稱): Xcode

一種解決方案是根據按鈕的位置獲取單元格的索引路徑。

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

您可以設置並檢查按鈕屬性“標簽”(如果已將插座設置為控制器)

這是另一個簡單的解決方案:

為回調有一個新屬性。

    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
    }

在單元格上,您可以進行練習

    cell class
    //...

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM