如何在swift中删除渐变层

时间:2017-12-26 10:29:37

标签: swift3 cagradientlayer

Code:

    extension CAGradientLayer
    {
        func changeStatusBarColor() -> CAGradientLayer
        {
            var height = 20
            let Size = UIScreen.main.bounds

            let darkViolet = UIColor(hexString: "#44377D")
            let lightViolet = UIColor(hexString: "##686CCD")

            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = CGRect(x: 0, y: 0, width:Int(Size.width), height: height)
            gradientLayer.colors =  [darkViolet,lightViolet ].map{$0.cgColor}
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
            return gradientLayer
        }
    }

     let gradientLayer = CAGradientLayer()
            gradientLayer.name = "masklayer"
            self.view.layer.addSublayer(gradientLayer.changeStatusBarColor())

            for layer in self.view.layer.sublayers! {
                print("layer name:", layer.name)
                if layer.name == "masklayer" {
                    layer.removeFromSuperlayer()
                }
            }

我为状态栏应用了渐变颜色。当我尝试使用上面的代码删除子图层时,它不会删除子图层。我的代码有什么问题。任何帮助都会被预先提交。谢谢提前

1 个答案:

答案 0 :(得分:0)

extension CAGradientLayer
{
    func changeStatusBarColor() -> CAGradientLayer
    {
        var height = 20
        let Size = UIScreen.main.bounds

        let darkViolet = UIColor(hexString: "#44377D")
        let lightViolet = UIColor(hexString: "##686CCD")

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(x: 0, y: 0, width:Int(Size.width), height: height)
        gradientLayer.colors =  [darkViolet,lightViolet ].map{$0.cgColor}
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

        gradientLayer.name = self.name

        return gradientLayer
    }
}

在changeStatusBarColor()函数中添加 gradientLayer.name = self.name