在 SWIFT 中使用协议和委派



我正在尝试将信息从一个集合视图单元格传递到另一个视图控制器,然后关闭视图控制器。我正在尝试与授权一起做到这一点,因为我认为这是唯一的方法,到目前为止,我已经建立了我的协议,如下所示:

@objc protocol CollectionViewImageDelegate {
   optional func selectedCell(row: NSIndexPath, data: UIImage) 
}

我添加了属性:

var delegate : CollectionViewImageDelegate?

然后在didSelectItemAtIndexPath中称呼它

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
        let imageData = self.sources[indexPath.row] 
        self.delegate?.selectedCell?(indexPath, data: imageData) 
        self.dismissViewControllerAnimated(true, completion: nil)
}

那么到目前为止,我如何称它为其他视图控制器:

class ProfileViewController: UIViewController, CollectionViewImageDelegate {
var colViewImage : CollectionViewVC

在视图中确实加载了:

colViewImage.delegate = self 

而这但什么也没发生:

func selectedCell(row: NSIndexPath, data: UIImage) {
    println(data) //Nothing prints
}

没有什么是打印我不知道为什么?我是协议和代表等的新手,似乎无法弄清楚为什么它没有传递图像?

谢谢

您的 CollectionViewController 正在调用此 selectedCell 方法,但您尚未链接委托。

使你的其他 ViewController 符合 collectionViewImageDelegate(通常应该用大写字母拼写),并在其中实现你的方法 selectedCell。

将 ViewController 设置为 CollectionViewController 的委托。

此外,将self.delegate?.selectedCell!(indexPath, data: imageData)更改为self.delegate?.selectedCell?(indexPath, data: imageData),以仅当可选方法 selectedCell 由委托实现时才调用该方法。

最新更新