Add gradient to the view(Swift)

When you want to give the background color to the view, but you want to add more colors and get the gradient effect, you need to add layer to view,
which we are going to create, in few lines of code

Akshay Somkuwar

--

#Step 1:
Create a CAGradientLayer

var gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [#Color1, #Color2]//Colors you want to add
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.frame = CGRect.zero
return gradientLayer
}()

#Step 2:
Add this gradientLayer to layer of your view

yourView.layer.addSublayer(gradientLayer)

#Step 3
Set frame of the gradientLayer

gradientLayer.frame = yourView.bounds

Here is the output…😊

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Akshay Somkuwar
Akshay Somkuwar

Written by Akshay Somkuwar

iOS | MacOS | React Native Developer..

Responses (2)

Write a response