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

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()
}

Leave a Comment