Swift: 将 UIImage 设置为背景

Swift: Setting UIImage as Background

我在 viewDidLoad() 中的行抱怨没有!在以下语句中:

 view.backgroundColor = UIColor.colorWithPatternImage(UIImage(named: "background.jpg"))

但是,当我按照建议将其更改为:

 view.backgroundColor = UIColor.colorWithPatternImage(UIImage(named: "background.jpg")!)

它给出了以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

再一次,我们将不胜感激!

将您的代码更改为:

if let image = UIImage(named: "background.jpg") {
    view.backgroundColor = UIColor.colorWithPatternImage(image)
} else {
    println("There was no such image as background.jpg")
}

这样你就不会崩溃,println 将登录到控制台并向你证明图像不存在 - 当然,直到它存在。