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

我试图在 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()

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

解决方法

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

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,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则不行,因为frame属性包含视图的位置和大小,即使你设置了渐变的帧大小,你没有指定渐变的位置……所以渐变从未实际添加到视图中.通过将frame属性直接设置为视图的边界,还可以在视图中添加渐变的位置.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...