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

时间:2016-05-13 09:53:57

标签: ios xcode swift2 uicollectionview uicollectionviewcell

我使用主要类别newsFeedCointroller作为UICollectionViewController。 1.在单元格内部我有一个带有类似按钮的新闻源(填充单元格我使用一个名为&#34的类; FeedCell") 2.从单元格(在主视图中)我有一个标签(labelX)用于"泼水消息"使用名为" messageAnimated"

的函数

如何拨打" messageAnimated"从单元格内的按钮开始工作。

我想将标签文字更改为例如:"您只是喜欢它" ...

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

在您的FeedCell中,您应该声明一个委托(阅读委托模式here

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()
    }
}