iOS Creating a gradient background view


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.