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?
This is the updated answer of my previous one.
As the same approach of my previous answer, You can create an extension of UIView and add
addBackground()
method to it, as follows:Remember: if you are adding it in a new .swift file, remember to add
import UIKit
Note that the updates for this answer are:
Usage:
Assuming that you want to call it in
viewDidLoad()
:Here are your options for scaling!
For the .contentMode property:
ScaleToFill This will scale the image inside the image view to fill the entire boundaries of the image view.
ScaleAspectFit This will make sure the image inside the image view will have the right aspect ratio and fit inside the image view’s boundaries.
ScaleAspectFill This will make sure the image inside the image view will have the right aspect ratio and fill the entire boundaries of the image view. For this value to work properly, make sure that you have set the clipsToBounds property of the imageview to true.
This uses PureLayout. You could just use AutoLayout with a few more lines.