How to make gradients in iOS using Swift

Yogesh Manghnani
codeburst
Published in
2 min readFeb 19, 2019

--

Making gradients in Swift has never been easier. There are two ways by which the result can be achieved.

  1. Using a wrapper UIView sub class for CAGradientLayer
  2. Using CAGradientLayer

Have a look at both of the files below

The first file is a UIView subclass that wraps around the important end points of the CAGradientLayer class. The GradientWrapperView can be add a subview of any View and used easily. All the necessary class properties can be set. And they reflect the changes in real time.
But with ease comes inefficiency. Rendering unnecessary UIView just for the sake of logical correctness of the program isn’t a good programming practice.

The second file uses CAGradientLayer directly. This is good for efficiency because there aren’t any unnecessarily rendered UIView. This method may bug some new developers once familiar it becomes the most handy technique.

Important Properties of CAGradientLayer and it’s custom wrapper (GradientWrapperView)

var colors: [Any]?
An array of CGColorRef objects defining the color of each gradient stop. Animatable.
The array of the CGColor will define the colors of the gradient.

var endPoint: CGPoint
The end point of the gradient when drawn in the layer’s coordinate space. Animatable.
The endPoint is a CGPoint. When you use this, keep in mind that here the range of x and y axis is 0 to 1.

var startPoint: CGPoint
The start point of the gradient when drawn in the layer’s coordinate space. Animatable.
The startPoint is a CGPoint. When you use this, keep in mind that here the range of x and y axis is 0 to 1.

var type: CAGradientLayerType
Style of gradient drawn by the layer.
I generally use .axial and .radial when I have to use this as a background of a ViewController.

--

--

I am fullstack developer who can’t sleep with bugs. (both in bed and in code)