在`didFinishPickingMediaWithInfo`之后推送到另一个控制器时崩溃 [英] Crash when pushing to another controller after `didFinishPickingMediaWithInfo`

查看:63
本文介绍了在`didFinishPickingMediaWithInfo`之后推送到另一个控制器时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用户从选择器中选择一张照片后,我正在尝试让该应用转到其他视图控制器.

I'm trying to have the app go to a different view controller after the user chooses a photo from the picker.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage {

        let previewController = self.storyboard?.instantiateViewController(withIdentifier: "previewVC") as! PreviewViewController
        previewController.previewImage.image = image
        previewController.navigationItem.setHidesBackButton(true, animated: false)
        self.navigationController?.pushViewController(previewController, animated: true)
    }
}

previewController仅具有一个图像视图(@IBOutlet weak var previewImage: UIImageView!)和一个用于发布照片的按钮,因此我试图设置该图像视图以显示拾取的图像.

previewController simply has an image view (@IBOutlet weak var previewImage: UIImageView!) and a button to post the photo, so I'm trying to set that image view to display the picked image.

但是,我在previewController.previewImage.image = image行上出现了崩溃解开可选值时意外发现nil".在调试器中,PreviewController中的previewImage为nil,但我不确定为什么-用户单击选择器中的选择"后是否立即设置了该值?

However, I get a crash "unexpectedly found nil when unwrapping an optional value" on the previewController.previewImage.image = image line. previewImage in the previewController is nil in the debugger, but I'm not sure why - isn't that being set as soon as the user hits "choose" in the picker?

这里还有其他步骤吗?

推荐答案

问题的主要原因是您试图过早访问视图控制器的插座.实例化视图控制器后,不会立即创建和分配视图控制器的视图和出口.

The primary cause of your issue is that you are trying to access the outlets of the view controller too soon. The view controller's views and outlets are not created and assigned immediately after instantiating the view controller.

尝试从该视图控制器外部的代码直接访问该视图控制器的视图的设计也很糟糕.在这种情况下,正确的解决方案是添加可以设置的UIImage属性.然后,让视图控制器在适当的时间(例如在viewDidLoad中)基于该图像属性的值更新其自己的图像视图.

It's also poor design to attempt to directly access the views of a view controller from code outside of that view controller. The proper solution, in this case, is to add a UIImage property that you can set. Then let the view controller update its own image view based on the value of that image property at the proper time (such as in viewDidLoad).

这篇关于在`didFinishPickingMediaWithInfo`之后推送到另一个控制器时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆