Maxi Wainberg
Maxi Wainberg

Reputation: 1

How to call an outside function from button in cell

I use a main class call newsFeedCointroller as 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"

How can I call the "messageAnimated" function from the button inside the cells.

I want to to change the label text to for example: "you just liked it"...

Thanks for helping me

Upvotes: 0

Views: 311

Answers (1)

Tien
Tien

Reputation: 2215

In your FeedCell you should declare a delegate (Read about delegate pattern here)

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

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

Upvotes: 3

Related Questions