FullerPrime FullerPrime - 1 year ago 126
Swift Question

How do I set a background image in iOS with transparency using Swift?

I'm able to set a patterned background using the following code

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

It works fine but the image is a png with transparency and I think because of this the transparent areas are coming our as black, is there a way of enabling the transparency so the background colour shows through?

Answer Source

You see a black background, because there is no view behind the view you are modifying.

If you can't change your image (to make it non-transparent), you could add a subview to your view containing this image:

//create a new UIView
let otherView = UIView(frame: view.frame)
otherView.backgroundColor = UIColor(patternImage: UIImage(named: "imagefilename")!)

//now add your new view as subview to the existing one

The transparent parts should now be white by default. You can change this by modifying view.backgroundColor.

Note: If you add other UI-elements, they might be hidden under otherView because they are added as subviews of view. To prevent this, you can add them as subview of otherView or reorder the layers. (view.bringSubviewToFront(anotherUIElement))

I wrote all the code on the fly, so there might be some syntax errors. But the general idea behind this code should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download