每当离开应用程序然后返回时,渐变会变暗

Gradient gets darker whenever leaving app and then coming back

所以我在 UIView 子类的下半部分实现了一个简单的渐变,如下所示

但是,每次我离开应用程序并重新进入时,渐变都会变暗,等等。我该怎么做才能保持相同的颜色?

这是我的渐变代码。我不知道将它放在 layoutSubviews 中是否正确,但我无法通过直接调用渐变代码来使其工作,例如在 viewDidLoad 中:

override func layoutSubviews() {
   let gradientLayer = CAGradientLayer()
   gradientLayer.type = .axial
   gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
   gradientLayer.frame = bounds
   gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
   gradientLayer.endPoint = .init(x: 0, y: 1)
   gradientLayer.zPosition = 1
   gradientLayer.opacity = 0.5
   layer.addSublayer(gradientLayer)
}

layoutSubviews() 被多次调用,因此您的渐变被重复添加。 layoutSubviews() 并不是真正要添加此渐变的地方。在 viewDidLoad() 中添加它对您不起作用的原因是视图的 bounds 尚未建立。继续并在 viewDidLoad() 中设置渐变。将 gradient 保留为 属性,并使用 viewDidLayoutSubviews() 更新框架。

class ViewController: UIViewController {

    let gradientLayer = CAGradientLayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        gradientLayer.type = .axial
        gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = .init(x: 0, y: 1)
        gradientLayer.zPosition = 1
        gradientLayer.opacity = 0.5
        view.layer.addSublayer(gradientLayer)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        gradientLayer.frame = view.bounds
    }
}

对于 UIView 的子类视图,您可以这样处理:

class MyView: UIView {
    
    let gradientLayer = CAGradientLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addGradient()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        addGradient()
    }
    
    func addGradient() {
        gradientLayer.type = .axial
        gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = .init(x: 0, y: 1)
        gradientLayer.zPosition = 1
        gradientLayer.opacity = 0.5
        layer.addSublayer(gradientLayer)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
    }
}