Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 使用协议传递数据失败_Swift_Delegates_Swift Protocols - Fatal编程技术网

Swift 使用协议传递数据失败

Swift 使用协议传递数据失败,swift,delegates,swift-protocols,Swift,Delegates,Swift Protocols,您好,我的自定义代理在传递数据时遇到问题,请帮助所有人这是我的代码 protocol VideoCellDelegate { func didSaveFavorite(for cell: SearchVideoCell) } 我把我的代表放在SearchVideoCell class SearchVideoCell: UICollectionViewCell { var delegate: VideoCellDelegate? @objc func handleFavorite()

您好,我的自定义
代理在传递数据时遇到问题,请帮助所有人这是我的代码

protocol VideoCellDelegate {
    func didSaveFavorite(for cell: SearchVideoCell)
}
我把我的
代表
放在
SearchVideoCell

class SearchVideoCell: UICollectionViewCell {

var delegate: VideoCellDelegate?
@objc func handleFavorite() {
    print("Handling favorite")
    delegate?.didSaveFavorite(for: self)
}
这是我在
SearchVideoCell

class SearchVideoCell: UICollectionViewCell {

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

class SearchVideoController: UICollectionViewController, UICollectionViewDelegateFlowLayout, VideoCellDelegate
然后我调用了
代理
,但它不起作用,它只是打印
处理收藏夹
而不是
将视频保存到收藏夹

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

在您的
SearchVideoController
中,您是否已按如下所示分配了单元格的代表

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

    cell.delegate = self

    return cell

}

创建单元格时,可能没有将控制器设置为委托对象

//在控制器中

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

谢谢。我忘了在单元格中为项目分配我的代表。你们都有相同的答案谢谢,我忘了在单元格中为项目分配我的代表。你们都有相同的answer@ferryawijayanto但您不能同时接受(勾选)两个答案,因为没有选择;)