【问题标题】:failed passed data with protocol使用协议传递数据失败
【发布时间】:2018-11-08 03:32:12
【问题描述】:

您好,我在使用自定义 delegate 传递数据时遇到问题,请帮助大家这是我的代码

protocol VideoCellDelegate {
    func didSaveFavorite(for cell: SearchVideoCell)
}

我把我的delegate 放在SearchVideoCell 里面

class SearchVideoCell: UICollectionViewCell {

var delegate: VideoCellDelegate?

这是我在SearchVideoCell中的函数

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

比我尝试传入的SearchVideoController

class SearchVideoController: UICollectionViewController, UICollectionViewDelegateFlowLayout, VideoCellDelegate

比我打电话给delegate 但它不起作用,它只打印Handling Favorite 而不是saving video to favorite

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

【问题讨论】:

    标签: swift delegates swift-protocols


    【解决方案1】:

    在您的SearchVideoController 中,您是否按如下方式分配了您的单元格的代表?

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

    【讨论】:

    • 谢谢它有效,我忘记在单元格中为项目分配我的代表。你们都有相同的答案
    • @ferryawijayanto 但你不能接受(勾选)这两个答案,因为没有选项;)
    【解决方案2】:

    你可能在制作单元格时没有将控制器设置为委托对象。

    //在你的控制器中

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

    【讨论】:

    • 谢谢它有效,我忘记在单元格中为项目分配我的代表。你们都有相同的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2021-12-09
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多