iOS Set View Background Creating a gradient background view

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

To create a background with a gradient you can use the CAGradientLayer class:

Swift 3.1:

func createGradient() { 
    let caLayer = CAGradientLayer()
    caLayer.colors = [UIColor.white, UIColor.green, UIColor.blue]
    caLayer.locations = [0, 0.5, 1]
    caLayer.bounds = self.bounds
    self.layer.addSublayer(caLayer) 
}

This can be called on viewDidLoad() like so:

override func viewDidLoad() {
    super.viewDidLoad()
    createGradient()
}

The CAGradientLayer locations and bounds variables can take multiple values to create a gradient layer with how ever many colors you desire. From the documentation:

By default, the colors are spread uniformly across the layer, but you can optionally specify locations for control over the color positions through the gradient.



Got any iOS Question?