anusha hrithi anusha hrithi - 4 months ago 8
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

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:

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

var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

self.view.backgroundColor = UIColor(patternImage: image)