首页 > 解决方案 > 可选类型“UIImage?”的值 未拆封;你的意思是用'!' 或者 '?'?插入 '!'

问题描述

当我为视图控制器设置背景图像时,我遇到了一些这样的错误......

Error:    Value of optional type 'UIImage?' not unwrapped; did you mean to use '!' or '?'? Insert '!'

我的代码是...

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.view.backgroundColor = UIColor(patternImage: UIImage(named: "image.png"))

}

在此处输入图像描述

标签: iosswiftcocoa-touchuiimageviewuiimage

解决方案


使固定 :

let image = UIImage(named: "image.png")
if image != nil {
    self.view.backgroundColor = UIColor(patternImage:image)
}

因为UIImage(named: "image.png"),这将返回可选的图像对象。即如果图像不可用,它将返回 nil。

来自苹果文档

返回值

指定文件的图像对象,如果方法找不到指定的图像,则返回 nil。


推荐阅读