将捕获/画廊图像从一个ViewController传递到另一个

时间:2019-05-14 16:56:42

标签: swift uiviewcontroller uiimage segue

我想捕获照片或从画廊中挑选照片,然后将其在imageView内部传递给另一个ViewController。我成功制作了续集,但我不知道如何从imagePickerController传递图像。

第一个ViewController

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let selectedImage = info[.originalImage] as? UIImage{
            imagePicker.dismiss(animated: true){
                self.performSegue(withIdentifier: "goToCropScreen", sender: self)
            }

        }

    }

    //Navigation to other screens
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToCropScreen"{
            let destinationVC = segue.destination as! CropViewController
            destinationVC.imageToCrop = //Here is the problem. Idont know what image to use.
        }
    }

第二个ViewController

class CropViewController: UIViewController {

    @IBOutlet weak var cropImageView: UIImageView!

    var imageToCrop : UIImage?

    override func viewDidLoad() {
        super.viewDidLoad()

        cropImageView.image = imageToCrop

    }


}

我知道我不能使用selectedImage,因为它位于imagePickerController内部。有没有办法像全局使用它。

1 个答案:

答案 0 :(得分:1)

在FirstViewController中创建一个变量。并将所选图像存储在此变量中,然后通过prepare for segue方法传递值

class FirstViewController: UIViewController {

    var selectedImage: UIImage?

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            if let selectedImage = info[.originalImage] as? UIImage{
                imagePicker.dismiss(animated: true){
                    self.selectedImage = selectedImage
                    self.performSegue(withIdentifier: "goToCropScreen", sender: self)
                }

            }

        }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToCropScreen"{
            let destinationVC = segue.destination as! CropViewController
            destinationVC.imageToCrop = self.selectedImage
        }
    }
}