Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Background gradient for UIView

Tags:

ios

swift

uiview

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

like image 325
gmoraleda Avatar asked Apr 26 '18 07:04

gmoraleda


People also ask

How do you make a gradient in Swift?

gradient. startPoint = CGPoint(x: 0.0, y: 1.0) gradient. endPoint = CGPoint(x: 1.0, y: 1.0) for different gradient position.


1 Answers

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)
    }
    
like image 154
gmoraleda Avatar answered Sep 20 '22 07:09

gmoraleda