J.Doe J.Doe - 1 year ago 66
iOS Question

CAGradientLayer not changing the background color

I want to create a gradient as a background color for my UIView. I wrote this code

gradient.colors = [UIColor.blue,UIColor.yellow]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)


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


but the view still the same set on the Interface Builde. If I add this line before the code

self.view.backgroundColor = UIColor.clear


the background color changes to white

Answer Source
        let gradient: CAGradientLayer = CAGradientLayer()

        gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
        gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)

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

try this code. It works for me swift 3

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download