Swift: Background gradient for UIView

Update your method to the code blow:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor){
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [colorTop.cgColor, colorBottom.cgColor]
    gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
    gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
    gradientLayer.locations = [NSNumber(floatLiteral: 0.0), NSNumber(floatLiteral: 1.0)]
    gradientLayer.frame = self.bounds

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

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)
    }
    

Tags:

Ios

Uiview

Swift