如何将渐变添加到UIView作为扩展

时间:2017-02-02 18:53:31

标签: ios swift

我正在尝试在Xcode中为视图添加一些渐变,为了简单起见,我尝试将我的方法添加为UIView的扩展:

extension UIView {
    func applyGradient() {
        let gradient = CAGradientLayer()
        gradient.colors = [UIColor(hex: "F5FF8C").cgColor,
                           UIColor(hex: "F1F99D").cgColor,
                           UIColor(hex: "FDFFE0").cgColor]
        gradient.locations = [0.0, 0.5, 1.0]

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

但显然当我在viewDidLoad中调用它时,这不起作用:

self.myView.applyGradient()

有人能指出我做错了什么吗?

1 个答案:

答案 0 :(得分:8)

在问题中,您根本没有设置框架。在评论中,您的框架设置不正确。这是应该正常工作的代码:

extension UIView {
    func applyGradient() {
        let gradient = CAGradientLayer()
        gradient.colors = [UIColor.red.cgColor,
                           UIColor.green.cgColor,
                           UIColor.black.cgColor]   // your colors go here
        gradient.locations = [0.0, 0.5, 1.0]
        gradient.frame = self.bounds
        self.layer.insertSublayer(gradient, at: 0)
    }
}

使用您的代码:

enter image description here

修改后的代码:

enter image description here

说明

gradient.frame.size = self.frame.size无法正常工作,而gradient.frame = self.bounds则有效,因为框架属性包含视图的位置和大小,即使您设置了渐变的帧大小,您不指定渐变的位置...因此渐变从未实际添加到视图中。通过将框架属性直接设置为视图的边界,您还可以在视图中添加渐变的位置。