I'm having trouble trying to add a gradient background to UIView
. I made an extension
of UIView
and added the following method:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
}
Then I call:
separatorView.setGradientBackground(colorTop: .clear, colorBottom: .red)
But it doesn't work. The view is presented but its background is entirely clear. I tried as well with CGColor
gradient. startPoint = CGPoint(x: 0.0, y: 1.0) gradient. endPoint = CGPoint(x: 1.0, y: 1.0) for different gradient position.
There were 2 problems:
I needed to set the start and end points to provide a gradient direction:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.locations = [0, 1]
gradientLayer.frame = bounds
layer.insertSublayer(gradientLayer, at: 0)
}
And the second issue was that CAGradientLayer
takes effect after the view is layed out. I solved that calling setGradientBackground()
on viewDidAppear
:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
separatorView.setGradientBackground(colorTop: .clear, colorBottom: Colors.darkGrey)
}
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