CAGradientLayer Tutorial — How to Create a Gradient with Swift 5
CAGradientLayer
CAGradientLayer is a CALayer type where you can create gradients. You can use as many colors as you want and modify other attributes like the angle and positions. You can use this to create gradients for your app’s background or for customizing a button’s appearance.
Xcode Set Up
Open up Xcode and select Create a new Xcode project, and under the iOS tab choose App and click Next. Give a name to Product Name and make sure for Interface you choose Storyboard. Select Swift for Language and unchecked the options and click Next to choose a location to save your project.
CAGradientLayer()
Go to the ViewController file. Here we will create a new function called setGradientBackground() and also call that function in viewDidLoad(). Declare a new CAGradientLayer() and set it to a constant called gradientLayer. Next, we will choose the colors we will use for the gradient. In this case we set a gradient using blue and cyan. Add the colors in an array for gradientLayer.colors. It is important that you set each color as a cgColor in order for the gradient to work.
func setGradientBackground() { let gradientLayer = CAGradientLayer()