xcode 如何将图片分配给 UIImageView (Swift 3)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41064561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:38:23  来源:igfitidea点击:

How to assign a picture to the UIImageView (Swift 3)

iosswiftxcode

提问by nik3212

I'm trying to add an image from the gallery to the new ViewController, but get an error

我正在尝试将图库中的图像添加到新的 ViewController,但出现错误

Creating an image format with an unknown type is an error fatal error: unexpectedly found nil while unwrapping an Optional value

使用未知类型创建图像格式是一个错误致命错误:在解包可选值时意外发现 nil

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?

我的错误是什么?

回答by Dule

Your EditImageViewController.imageViewis nil. To pass image from outside, you need to add UIImage property to EditImageViewController.

EditImageViewController.imageView的为零。要从外部传递图像,您需要将 UIImage 属性添加到EditImageViewController.

To assign that image to UIImageView, use viewDidLoad()

要将该图像分配给UIImageView,请使用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 = imbecomes vc.imageToAdd = im

要将图像传递给新控制器,只需设置imageToAdd,就vc.imageView.image = im变成vc.imageToAdd = im