Swift 3 - 无法将图像从一个viewcontroller传递到第二个

时间:2017-11-10 10:52:13

标签: ios swift uiimagepickercontroller

我正试图通过prepareforSegue将图像从第1 UIViewController传递到第2 UIViewControlleler

我的代码: -

extension ViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func handleImg() {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.allowsEditing = true
    present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var selectedImageFromPicer : UIImage?
    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        selectedImageFromPicer = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {

        selectedImageFromPicer = originalImage
    }

    if let selectedImage = selectedImageFromPicer {
        imgg.image = selectedImage  
    }
    guard let imageUrl = info["UIImagePickerControllerImageURL"] as? URL else {
        return
    }
    self.performSegue(withIdentifier: "selected", sender: self)
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("canceled picker")
        dismiss(animated: true, completion: nil)
    }
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "selected" {
        let vc = segue.destination as! secondVC
        vc.img.image = self.imgg.image

    }
}

我收到了vc.img.image = self.imgg.image

行的错误

错误

  

致命错误:在解包可选值时意外发现nil

2 个答案:

答案 0 :(得分:0)

由于self.imgg.image为零,您收到该错误。所以你只是在它不是空的时候设置imgg:

if let selectedImage = selectedImageFromPicer {
    imgg.image = selectedImage  
}

但是如果这段代码永远不会运行,那么它会抛出一个意外发现的错误。

因此,当您为第二个VC设置它时,首先检查它是否为空,然后将其设置为:

vc.img.image = self.imgg.image

答案 1 :(得分:0)

在UIImage类型的secondVC中创建变量,并从该变量中的第一个viewcontroller设置图像

您将收到此异常,因为尚未在内存中创建secondVC的视图。

所以在FirstVC中应用以下更改

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "selected" {
        let vc = segue.destination as! secondVC
        vc.image = self.imgg.image

    }
}

在secondVC中应用以下更改

声明var image: UIImage? = nil

并在viewDidLoad()中将image设置为imageView

override func viewDidLoad() {
    super.viewDidLoad()
    self.img.image = image
}