如何在运行时更改渐变层的框架?

时间:2019-06-18 05:36:37

标签: ios swift gradient

当我运行应用程序时,渐变层框架与UIView框架不匹配。我尝试了以下代码:

let color1  =  UIColor(red: 20.0/255, green: 43.0/255, blue: 81.0/255, alpha: 1.0).cgColor
let color2  =  UIColor(red: 149.0/255, green: 45.0/255, blue: 122.0/255, alpha: 1.0).cgColor

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.backBarcodeSrch.bounds
gradientLayer.colors =  [color1,color2 ]
gradientLayer.locations = [0.0, 1.0]

gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.6)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.6)
self.backBarcodeSrch.layer.addSublayer(gradientLayer)

2 个答案:

答案 0 :(得分:2)

更新您framegradientLayerviewDidLayoutSubviews()ViewController的{​​{1}}。

class VC: UIViewController {
    var gradientLayer = CAGradientLayer()

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        gradientLayer.frame = self.backBarcodeSrch.bounds
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addGradient()
    }

    func addGradient() {
        let color1  =  UIColor(red: 20.0/255, green: 43.0/255, blue: 81.0/255, alpha: 1.0).cgColor
        let color2  =  UIColor(red: 149.0/255, green: 45.0/255, blue: 122.0/255, alpha: 1.0).cgColor

        gradientLayer.frame = self.backBarcodeSrch.bounds
        gradientLayer.colors =  [color1,color2 ]
        gradientLayer.locations = [0.0, 1.0]

        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.6)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.6)
        self.backBarcodeSrch.layer.addSublayer(gradientLayer)
    }
}

答案 1 :(得分:1)

尝试:

func addGradientLayer() {
let color1  =  UIColor(red: 20.0/255, green: 43.0/255, blue: 81.0/255, alpha:1.0).cgColor
let color2  =  UIColor(red: 149.0/255, green: 45.0/255, blue: 122.0/255, alpha: 1.0).cgColor

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.backBarcodeSrch.bounds
gradientLayer.colors =  [color1,color2 ]
gradientLayer.locations = [0.0, 1.0]

gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.6)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.6)
self.backBarcodeSrch.layer.addSublayer(gradientLayer)

}

override func viewDidLayoutSubviews() {
addGradientLayer()
}