How to set background image in fast?

I am trying to set an image around your ViewController in a fast language.

I am using the following code:

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

But the application gets crash.It shows an error like

"fatal error: unexpectedly found zero when deploying an optional value" (due to "!")

+7
ios swift uiimage
source share
3 answers

This error occurs because the image "bg.png" does not exist. Typically, when you import images into the Assets.xcassets folder, the file extension is deleted. 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 described here :

  UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "bg")?.draw(in: self.view.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) 
+16
source share

Try this Swift4:

 let backgroundImage = UIImageView(frame: UIScreen.main.bounds) backgroundImage.image = UIImage(named: "bg.png") backgroundImage.contentMode = UIViewContentMode.scaleAspectFill self.view.insertSubview(backgroundImage, at: 0) 
+2
source share

Update for swift3:

  UIGraphicsBeginImageContext(self.frame.size) UIImage(named: "bg").draw(in: self.bounds) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() backgroundColor = UIColor(patternImage: image) 
0
source share

All Articles