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

Swift 3 - Unable to pass image from one viewcontroller to second

我正在尝试通过 prepareforSegue

将图像从第一个 UIViewController 传递到第二个 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

行收到错误

错误

fatal error: unexpectedly found nil while unwrapping an Optional value

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

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

但是如果此代码永远不会 运行 怎么办,那么它将抛出意外发现 nil 的错误。

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

vc.img.image = self.imgg.image

在类型为 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

    }
}

在第二个 VC 中应用以下更改

声明var image: UIImage? = nil

然后在 viewDidLoad() 中将图像设置为 imageView

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