簡體   English   中英

如何從單元格中的按鈕調用外部函數

[英]How to call an outside function from button in cell

我使用主類調用newsFeedCointroller作為UICollectionViewController 1.在內部的單元格中,我有一個帶有“喜歡”按鈕的新聞源(要填充該單元格,我使用了一個名為“ FeedCell”的類)。2.從單元格中(在主視圖中),我有一個標簽(labelX)用於“啟動消息”,一個名為“ messageAnimated”的函數

如何從單元格內的按鈕調用“ messageAnimated”函數。

我想將標簽文本更改為例如:“您剛剛喜歡它” ...

謝謝你幫我

在FeedCell中,您應該聲明一個委托( 在此處閱讀有關委托模式的信息

protocol FeedCellDelegate {
    func didClickButtonLikeInFeedCell(cell: FeedCell)
}

在單元實現中(假設您手動添加了目標)

var delegate: FeedCellDelegate?

override func awakeFromNib() {
    self.likeButton.addTarget(self, action: #selector(FeedCell.onClickButtonLike(_:)), forControlEvents: .TouchUpInside)
}

func onClickButtonLike(sender: UIButton) {
        self.delegate?.didClickButtonLikeInFeedCell(self)
}

在您的View控制器中

extension FeedViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
        // Do your setup.
        // ...
        // Then here, set the delegate
        cell.delegate = self
        return cell
    }

    // I don't care about other delegate functions, it's up to you.
}

extension FeedViewController: FeedCellDelegate {
    func didClickButtonLikeInFeedCell(cell: FeedCell) {
        // Do whatever you want to do when click the like button.
        let indexPath = collectionView.indexPathForCell(cell)
        print("Button like clicked from cell with indexPath \(indexPath)")
        messageAnimated()
    }
}

暫無
暫無

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

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