簡體   English   中英

如何從嵌套的collectionView單元格傳遞按鈕操作?

[英]How do I pass button action from a nested collectionView cell?

我有一個MainCollectionView用於在項目之間滾動,在其中一個單元格內我有另一個帶有單元格的collectionView。 在該集合視圖中,我為每個單元格都有一個按鈕。 我的問題是如何在點擊時將操作從我的按鈕傳遞到我的MainCollectionView? 我確實在單元格中為該按鈕創建了協議,但我不知道如何讓我的MainCollectionView知道何時點擊我的按鈕。 我可以從我的單元類中調用action,但我認為最好在Model中運行它,這是我的MainCollectionView。 下面是我的按鈕協議。

protocol ThanhCaHotTracksCellDelegate: class {
func handleSeeAllPressed()}

weak var delegate: ThanhCaHotTracksCellDelegate?


@objc func handleSeeAllButton(){
 delegate?.handleSeeAllPressed()
}

LIke NSAdi說,你正處於正確的軌道上,但代表模式只需要一個單獨的任務,比如通知按鈕按下。

我更喜歡使用閉包,因為它們很輕,並且有助於將相關代碼保持在一起。

使用閉包

這就是我在UITableView一直在做的事情。 所以這也適用於UICollectionView

class MyTableViewCell: UITableViewCell {
    var myButtonTapAction: ((MyTableViewCell) -> Void)?

    @IBAction func myButtonTapped(_ sender: Any) {
        myButtonTapAction?(self)
    }
}

因此,當我將我的單元格出列並將其轉換為MyTableViewCell我可以設置如下自定義操作:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "myCellReuseIdentifier", for: indexPath) as! MyTableViewCell

    cell.myButtonTapAction = { cell in
        // Put your button action here
        // With cell you have a strong reference to your cell, in case you need it
    }
}

使用直接參考

當您將UICollectionView單元格出列時,可以通過將單元格轉換為單元格的自定義子類來獲取對按鈕的引用。

然后只需執行以下操作

cell.button.addTarget(self, action: #selector(didTapButton(_:)), forControlEvents: .TouchUpInside)

外面有一個功能:

@objc func didTapButton(_ sender: UIButton) {
    // Handle button tap
}

缺點是您無法直接訪問您的手機。 你可以使用button.superview? 但這不是一個好主意,因為您的視圖層次結構可能會發生變化......

你走在正確的軌道上。

確保MainCollectionView(或包含它的類)實現ThanhCaHotTracksCellDelegate協議。

然后將delegate指定為self

就像是...

class ViewController: ThanhCaHotTracksCellDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        subCollectionView.delegate = self
    }
}

暫無
暫無

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

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