Have any Question?

You can ask below or enter what you are looking for!

Create UIView with gradient background

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


One Comment

  1. This works great on first load. However, if the user reorientates the device from portrait to landscape or vice versa, the gradient bounds are not updated. Does similar code need to be added to viewWillTransition or similar?

Leave a Reply

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