Create UIView with gradient background

Add gradient background to UIView using CAGradientLayer

Using CAGradientLayer

CAGradientLayer is a layer that draws gradient color over its background.

By default color are spread evenly but you can control the locations of them.



CAGradientLayer example

The following function will add a gradient layer to the view passed to it

func addGradientToView(view: UIView)
{
        //gradient layer
        let gradientLayer = CAGradientLayer()
        
        //define colors
        gradientLayer.colors = [UIColor.red.cgColor,    UIColor.green.cgColor, UIColor.blue.cgColor]
        
        //define locations of colors as NSNumbers in range from 0.0 to 1.0
        //if locations not provided the colors will spread evenly
        gradientLayer.locations = [0.0, 0.6, 0.8]
        
        //define frame
        gradientLayer.frame = view.bounds
        
        //insert the gradient layer to the view layer
        view.layer.insertSublayer(gradientLayer, at: 0)   
}

Note that locations of colors is an NSNumber array and every location must be in the range of 0.0 to 1.0

Call the addGradientToView(view: UIView) method in viewDidLoad and pass self.view as a parameter, this is what you get:

CAGradientLayer example

 

Leave a Reply

Your email address will not be published. Required fields are marked *