如何将 UIImagePickerController 与委托一起使用?

How to use UIImagePickerController with delegate?

我将 UIView (A Class) 作为 xib 实例添加到 ViewController。

我想通过操作(在 A Class 中)从 ViewController class 的 UIImagePickerController 获取图像并将其 return 到 A Class。

我写了下面的代码。 但是,我不知道如何 return 到 A Class.

我再次委托给 ViewController 但我放弃了,因为我显示了委托的各种错误。 [展开错误...,只是没有移动任何东西...等]。

// A Class
class A: CustomDelegate{
    var delegate001: PhotoLibraryDelegate!

    class func instance() -> A {
        return UINib(nibName: "A", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! A
    }

    @IBAction func openPhotoLibrary(_ sender: Any) {
        self.delegate001.selectPhoto() //I want photo in A Class XD. so make Delegate!!
    }
}

@objc protocol PhotoLibraryDelegate {
    func selectPhoto()
}

//ViewController Class
class ViewController: PhotoLibraryDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    let a = A.instance()

    override func viewDidLoad() {
        super.viewDidLoad()
        a.delegate006 = self
    }

    func selectPhoto() {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let pickerView = UIImagePickerController()
            pickerView.sourceType = .photoLibrary
            pickerView.delegate = self

            self.present(pickerView, animated: true)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as? UIImage // Yeah, I selected the image!!

        self.dismiss(animated: true)

        //... Wa!? I want to return "image" to A class. OMG.
    }
}

最简单的方法是你已经创建了A的实例class。现在直接把图片赋值给它就行了

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as? UIImage // Yeah, I selected the image!!

    a.imageView.image = image

    self.dismiss(animated: true)


}