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但您不能同时接受(勾选)两个答案,因为没有选择;)