使用协议传递数据失败
failed passed data with protocol
嗨,我在使用自定义 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")
}
在你的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
嗨,我在使用自定义 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")
}
在你的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