I'm trying to add an image from the gallery to the new ViewController, but get an error
Creating an image format with an unknown type is an error fatal error: unexpectedly found nil while unwrapping an Optional value
Code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let im = info[UIImagePickerControllerOriginalImage] as? UIImage {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "editImage") as! EditImageViewController
vc.imageView.image = im
self.present(vc, animated: true, completion: nil)
} else {
print("Something went wrong")
}
imagePicker.dismiss(animated: true, completion: nil)
}
What's my mistake?
Your EditImageViewController.imageView
is nil. To pass image from outside, you need to add UIImage property to EditImageViewController
.
To assign that image to UIImageView
, use viewDidLoad()
Something like this:
class EditImageViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var imageToAdd: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.image = imageToAdd
}
}
To pass image to new controller, just set imageToAdd
, so vc.imageView.image = im
becomes vc.imageToAdd = im
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.