UICollectionView协议问题

时间:2019-02-07 03:55:38

标签: ios swift

我有一个viewController通过一个动作按钮来呈现一个'CollectionViewController'。

@objc func addPhoto() {
    let layout = UICollectionViewFlowLayout()
    let photoController = UINavigationController(rootViewController: PhotoController(collectionViewLayout: layout))
    present(photoController, animated: true, completion: nil)
}

在“ PhotoController”内部,我试图使用标准协议过程将数据从此控制器传递回原始viewController。

protocol PhotoControllerDelegate {
    func store(image: UIImage)
}

var delegate: PhotoControllerDelegate?

@objc func handleSave() {
    if let image = headerImage {
        delegate?.store(image: image)
    }

    ///Dimiss viewController
    dismiss(animated: true, completion: nil)
}

现在回到原来的viewController中,我已经重新实例化了已关闭的PhotoController:

let photoController = PhotoController()

并在viewDidLoad()内部分配了委托

photoController.delegate = self

然后在原始viewController中提供了委托方法:

func store(image: UIImage) {
    selectedPhotoImage.image = image
}

问题是:甚至没有调用此方法。 我通常没有任何问题,但是这个问题困扰了我。

任何帮助都会很棒。

P.S。我的viewControllers内部有很多多余的垃圾,因此无法发布完整的代码。

1 个答案:

答案 0 :(得分:1)

请确保将delegate添加为self,以在该protocol中接收viewController事件

@objc func addPhoto() {
    let layout = UICollectionViewFlowLayout()
    let objVC = PhotoController(collectionViewLayout: layout)
    objVC.delegate = self
    let photoController = UINavigationController(rootViewController: objVC)
    present(photoController, animated: true, completion: nil)
}

不要忘记在同一delegate中添加viewController。使用extension使其代码干净。

extension SourceController: PhotoControllerDelegate {
    func store(image: UIImage) {
        selectedPhotoImage.image = image
    }
}

像下面的protocol一样定义PhotoController

public protocol PhotoControllerDelegate {
    func store(image: UIImage)
}