richc
richc

Reputation: 1678

How to set UIViewController background image to fill screen

I have a UIViewController that I want to set the background to one image. I want to do this in code not IB, so I can subsequently change the image.

Having read all the tips on here about .ScaleAspectFill my image still does not resize to fit the screen. Can anyone offer any advice please? The code I have is:

override func viewDidLoad() {
    super.viewDidLoad()

    // set the inital backgroundColor
    self.view.backgroundColor = UIColor(patternImage: gameBackgroundOne!)
    self.view.contentMode = UIViewContentMode.ScaleAspectFill //doesnt seem to do anything!
    self.view.clipsToBounds = true // is this needed?
    self.view.center = view.center // is this needed?
}

Upvotes: 2

Views: 7290

Answers (2)

RM_B
RM_B

Reputation: 101

It would be best to create a separate UIImageView for this.

var imageView: UIImageView!

override func loadView() {
    super.loadView()

    // get the correct image out of your assets cataloge
    let image = UIImage(named: "yourImageInAssets")!

    // initialize the value of imageView with a CGRectZero, resize it later
    self.imageView = UIImageView(frame: CGRectZero)

    // set the appropriate contentMode and add the image to your imageView property
    self.imageView.contentMode = .ScaleAspectFill
    self.imageView.image = image

    // add the imageView to your view hierarchy
    self.view.addSubview(imageView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    //set the frame of your imageView here to automatically adopt screen size changes (e.g. by rotation or splitscreen)
    self.imageView.frame = self.view.bounds

}

Upvotes: 5

Lukas
Lukas

Reputation: 3433

Create an image view, add the image to the image view and add the image view to your view hierarchy.

override viewDidLoad() {
    super.viewDidLoad()

    let imageView = UIImageView(frame: self.view.bounds)
    imageView.image = UIImage(named: "your image name")//if its in images.xcassets
    self.view.addSubview(imageView)
}

Upvotes: 1

Related Questions