简体   繁体   English

如何从单元格中的按钮调用外部函数

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

I use a main class call newsFeedCointroller as UICollectionViewController . 我使用主类调用newsFeedCointroller作为UICollectionViewController 1. In cell inside I have a newsfeed with a like button (to populate the cell I use a class called "FeedCell") 2. Out from cells (in mainview) I have a label (labelX) used for "splash message" with a function called "messageAnimated" 1.在内部的单元格中,我有一个带有“喜欢”按钮的新闻源(要填充该单元格,我使用了一个名为“ FeedCell”的类)。2.从单元格中(在主视图中),我有一个标签(labelX)用于“启动消息”,一个名为“ messageAnimated”的函数

How can I call the "messageAnimated" function from the button inside the cells. 如何从单元格内的按钮调用“ messageAnimated”函数。

I want to to change the label text to for example: "you just liked it"... 我想将标签文本更改为例如:“您刚刚喜欢它” ...

Thanks for helping me 谢谢你帮我

In your FeedCell you should declare a delegate (Read about delegate pattern here ) 在FeedCell中,您应该声明一个委托( 在此处阅读有关委托模式的信息

protocol FeedCellDelegate {
    func didClickButtonLikeInFeedCell(cell: FeedCell)
}

In your cell implementation (suppose that you add target manually) 在单元实现中(假设您手动添加了目标)

var delegate: FeedCellDelegate?

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

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

In your View controller 在您的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