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 ?
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:
With the modified code:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With