failed passed data with protocol

4155 views swift
-4

Hi I have a problem passing data with my custom delegate, please help everyone this is my code

protocol VideoCellDelegate {
func didSaveFavorite(for cell: SearchVideoCell)

}

and I put my delegate inside SearchVideoCell

class SearchVideoCell: UICollectionViewCell {

var delegate: VideoCellDelegate?

and this is my function inside SearchVideoCell

@objc func handleFavorite() {
    print("Handling favorite")
    delegate?.didSaveFavorite(for: self)
}

than I tried passed in in SearchVideoController

class SearchVideoController: UICollectionViewController, UICollectionViewDelegateFlowLayout, VideoCellDelegate

than I called the delegate but it's not working, it's only print "Handling Favorite" not "saving video to favorite"

func didSaveFavorite(for cell: SearchVideoCell) {
    print("saving video to favorite")
}

answered question

2 Answers

2

In your SearchVideoController, Have you assigned the delegate of your cell as like below?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchVideoCellID", for: indexPath) as! SearchVideoCell

    cell.delegate = self

    return cell

}

posted this
13

You probably haven't set the controller as the delegate object when you made the cell.

//In your controller

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! SearchVideoCell
cell.delegate = self

posted this

Have an answer?

JD

Please login first before posting an answer.