ios - 可选类型“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"))
}
解决方案
使固定 :
let image = UIImage(named: "image.png")
if image != nil {
self.view.backgroundColor = UIColor(patternImage:image)
}
因为UIImage(named: "image.png")
,这将返回可选的图像对象。即如果图像不可用,它将返回 nil。
返回值
指定文件的图像对象,如果方法找不到指定的图像,则返回 nil。
推荐阅读
- java - Docker 容器中的 Elasticsearch 内存使用问题
- json - Swift:可编码复杂的 JSON
- dart - 未定义的名称“上下文”
- python - Pandas-根据 Id 分组的当前行值更新上一行和下一行值
- flutter - Flutter - 自动调整大小的 AlertDialog 以适应列表内容
- reactjs - 如何在全日历中替换按日重复发生的特定事件?
- c# - 玩家移动其他物体 Unity 2D
- python - 如何在使用 CountVectorizer 制作训练数据集时修复“numpy.ndarray”错误?
- apache-spark - 如何停止在函数内部创建的 SparkContext?
- java - 如何使用 1:n 关系将数据批量插入到两个表中?