How do you make a background image scale to screen size in swift?

GuiGui23 picture GuiGui23 · Nov 26, 2014 · Viewed 89.6k times · Source

I'm trying to make a UIView image for my background in swift using pattern image. The code I have works well except for the fact that I want the image to take the whole screen. My code looks like this: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage")!)

Does anyone know how to make the background an image that will take up the whole screen, and would scale when appearing on different iPhone screen sizes?

Answer

Ahmad Fayyas picture Ahmad Fayyas · Oct 7, 2015

Note That:

I posted this answer from my old account (which is deprecated for me and I can't access it anymore), this is my improved answer.


You can do it programmatically instead of creating an IBOutlet in each view. just create a UIView extension (File -> New -> File -> Swift File -> name it whatever you want) and add:

extension UIView {
func addBackground() {
    // screen width and height:
    let width = UIScreen.mainScreen().bounds.size.width
    let height = UIScreen.mainScreen().bounds.size.height

    let imageViewBackground = UIImageView(frame: CGRectMake(0, 0, width, height))
    imageViewBackground.image = UIImage(named: "YOUR IMAGE NAME GOES HERE")

    // you can change the content mode:
    imageViewBackground.contentMode = UIViewContentMode.ScaleAspectFill

    self.addSubview(imageViewBackground)
    self.sendSubviewToBack(imageViewBackground)
}}

Now, you can use this method with your views, for example:

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addBackground()
}