如何使用UIImagePickerController与委托?

时间:2018-03-03 13:48:08

标签: ios swift uiimagepickercontroller

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

我想通过action(在A类中)从ViewController类的UIImagePickerController获取图像并将其返回给A类。

我写了以下代码。 但是,我不知道如何返回A级。

我再次委托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.
    }
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是您已经创建了A类的实例。现在直接将图像分配给它。

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)


}