Enamul Haque
Enamul Haque

Reputation: 843

How to add multiple gradient color in multiple views in a view controller

I use the code below for gradient color. But when I use that code it colors the whole view controller. It also covers the other contents too like textfield, label, etc. I want to use multiple views with multiple gradient colors in a view controller. Suppose I have three views in a view controller and I want to use three different gradient colors in three different views. Content like label and textfield will appear on the gradient colors.

Here is my code:

func setBackground_view() {
    let gradientLayer = CAGradientLayer()
    let colorTop =  UIColor(red: 44/255.0, green: 156/255.0, blue: 56/255.0, alpha: 1.0).cgColor
    let colorBottom = UIColor(red: 155/255.0, green: 180/255.0, blue: 23/255.0, alpha: 1.0).cgColor

    gradientLayer.colors = [ colorTop, colorBottom]
    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.frame = self.view.bounds
    self.view.layer.addSublayer(gradientLayer)
    self.view.layer.insertSublayer(gradientLayer, at: 0)
    view.layer.addSublayer(gradientLayer)
}

Upvotes: 0

Views: 1264

Answers (2)

Ladislav
Ladislav

Reputation: 7283

You are adding the sublayer 3 times with

self.view.layer.addSublayer(gradientLayer)
self.view.layer.insertSublayer(gradientLayer, at: 0)
view.layer.addSublayer(gradientLayer)

Just do

func setBackground_view() {
    let gradientLayer = CAGradientLayer()
    let colorTop =  UIColor(red: 44/255.0, green: 156/255.0, blue: 56/255.0, alpha: 1.0).cgColor
    let colorBottom = UIColor(red: 155/255.0, green: 180/255.0, blue: 23/255.0, alpha: 1.0).cgColor

    gradientLayer.colors = [ colorTop, colorBottom]
    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradientLayer.frame = self.view.bounds
    view.layer.insertSublayer(gradientLayer, at: 0)
}

Basically you want to have the gradientLayer below all other views that are added in the view controller, that is why you insert it as the bottom most layer by inserting it at index 0.

Upvotes: 0

KLD
KLD

Reputation: 160

What you're doing in your example is applying the gradient to self.view which is essentially the root view of the whole ViewController. Not only that, but you're also applying the same gradient onto the self.view multiple times.

What you want is to apply gradients to each element individually, not the self.view itself.

Suppose you've got a UITextfield, then just apply the gradient as you already did, but instead, apply it directly onto the desired object.

textField.layer.insertSublayer(gradientLayer, at: 0)
anyOtherView.layer.insertSublayer(differentGradient, at: 0)

And so on and so forth.

Note: Remember to apply the different gradients to their appropriate views, otherwise all the gradients will be the same.

Upvotes: 1

Related Questions