anusha hrithi anusha hrithi - 1 year ago 116
Swift Question

How to set background image in swift?

I am trying to set aground image to my ViewController in swift language.

I am using the following code :

self.view.backgroundColor = UIColor(patternImage: UIImage(named:”bg.png")!)

But the app is getting crash.It is showing the error like

“fatal error: unexpectedly found nil while unwrapping an Optional
value”(Because of the “!”)

Answer Source

That error is thrown because the image "bg.png" does not exist. Usually when you import images to the Assets.xcassets folder, the file extension is removed. So try the following:

self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg")!)

You will notice that the background will not look as expected, you need to do the following as explained here:

UIImage(named: "bg")?.drawInRect(self.view.bounds)

var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()


self.view.backgroundColor = UIColor(patternImage: image)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download