简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM