ios 以编程方式添加的gradientLayer不会剪裁到通过脚本添加的UIView

lsmd5eda  于 2023-06-07  发布在  iOS
关注(0)|答案(2)|浏览(228)

1.我有一个原型单元格,我在后面设置了一个UIView,使其具有纯色背景色(蓝色,以便在Storyboard中清楚地看到内容)。

1.然后我决定在某个点将这个背景颜色设置为渐变色(全部在prototypeCell类中):

override func awakeFromNib() {
     super.awakeFromNib()
     gradientBGView()
 }

 fileprivate func gradientBGView() {
     let gradient = CAGradientLayer()
     gradient.cornerRadius = 15
     gradient.frame = bgColorView.bounds //bgColorView is the UIView set in the @IBOutlet
     gradient.colors = [
         UIColor(red: 0.15, green: 0.19, blue: 0.22, alpha: 1.00).cgColor,
         UIColor(red: 0.39, green: 0.45, blue: 0.51, alpha: 1.00).cgColor ]
     gradient.startPoint = CGPoint(x: 0.0, y: 0.2)
     gradient.endPoint = CGPoint(x: 1.0, y: 0.8)
     bgColorView.layer.insertSublayer(gradient, at: 0)
     bgColorView.layer.cornerRadius = 15 // this was done to make the solid color completely hide behind the gradient. I may as well get rid of this solid color altogether in the very end
 }

在肖像模式下一切正常:

但是,一旦你将模拟器旋转到横向模式,似乎坚实的背景会按计划伸展(我在故事板中将其固定在所有侧面),但梯度保持不变,即使我有:

gradient.frame = bgColorView.bounds

如何强制渐变层像纯色一样拉伸?如何将此渐变正确地固定到UIView纯色的边界?

omvjsjqw

omvjsjqw1#

图层不会随视图自动调整大小。
将这个简单的UIView子类添加到您的项目中:

class GradientView: UIView {
    
    var gradientLayer: CAGradientLayer!
    
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        gradientLayer = self.layer as? CAGradientLayer

        // if you are using these properties as constants,
        //  you can set them here
        gradientLayer.cornerRadius = 15
        gradientLayer.colors = [
            UIColor(red: 0.15, green: 0.19, blue: 0.22, alpha: 1.00).cgColor,
            UIColor(red: 0.39, green: 0.45, blue: 0.51, alpha: 1.00).cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.2)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.8)

    }
    
}

然后,在脚本原型单元格中,将bgColorView的自定义类设置为GradientView(确保同时更改@IBOutlet连接):

@IBOutlet var bgColorView: GradientView!

如果颜色和起点/终点的值不同,也可以在运行时设置它们。例如,在cellForRowAt中:

cell.gradientLayer.colors = [
     UIColor(red: 0.15, green: 0.19, blue: 0.22, alpha: 1.00).cgColor,
     UIColor(red: 0.39, green: 0.45, blue: 0.51, alpha: 1.00).cgColor
]
cell.gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.2)
cell.gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.8)

现在,当单元格框架改变时,bgColorView框架也会改变(因为它被约束到单元格的contentView),渐变框架也会沿着改变大小。

5tmbdcev

5tmbdcev2#

你有没有尝试过覆盖viewDidLayoutSubviews(),因为有时我们必须等待渐变加载,所以最好在viewDidLayoutSubviews()中调用addGradient()方法。See if this helps

相关问题