CAGradientLayer不改变背景颜色

时间:2017-08-16 12:36:35

标签: ios swift uiview

我想为我的UIView创建一个渐变作为背景颜色。我写了这段代码

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)

但是Interface Builde上的视图设置仍然相同。如果我在代码

之前添加此行
self.view.backgroundColor = UIColor.clear

背景颜色变为白色

1 个答案:

答案 0 :(得分:1)

        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)

试试这段代码。它适用于我swift 3