Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add gradient to UIView as an extension

Tags:

ios

swift

I am trying to add some gradient to a view in Xcode and for simplicity I tried to add my method as an extension to UIView:

extension UIView {
    func applyGradient() {
        let gradient = CAGradientLayer()
        gradient.colors = [UIColor(hex: "F5FF8C").cgColor,
                           UIColor(hex: "F1F99D").cgColor,
                           UIColor(hex: "FDFFE0").cgColor]
        gradient.locations = [0.0, 0.5, 1.0]

        self.layer.insertSublayer(gradient, at: 0)
    }
}

But apparently this doesn't work when I call it in my viewDidLoad:

self.myView.applyGradient()

Can someone point to me what am I doing wrong ?

like image 481
Adrian Avatar asked Feb 02 '17 18:02

Adrian


1 Answers

In the question, you haven't set the frame at all. In the comment, your frame was not set correctly. This is the code that should work properly:

extension UIView {
    func applyGradient() {
        let gradient = CAGradientLayer()
        gradient.colors = [UIColor.red.cgColor,
                           UIColor.green.cgColor,
                           UIColor.black.cgColor]   // your colors go here
        gradient.locations = [0.0, 0.5, 1.0]
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
    }
}

With your code:

enter image description here

With the modified code:

enter image description here


Explanation

gradient.frame.size = self.frame.size doesn't work, while gradient.frame = self.bounds does, because the frame attribute contains both the location and the size of the view, and even if you set the gradient's frame size, you do not specify the location of the gradient... So the gradient is never actually added to the view. By setting the frame attribute directly to the bounds of the view, you also add the location of the gradient in the view.

like image 127
Mr. Xcoder Avatar answered Oct 11 '22 19:10

Mr. Xcoder