WY34
WY34

Reputation: 391

Gradient gets darker whenever leaving app and then coming back

so I am implementing a simple gradient on the lower half a UIView subclass like the followingenter image description here

however, every time I leave the app and reenter it, the gradient gets darker, and so forth. How do I make it so it just stays the same shade?enter image description here

Here is my code for the gradient. I don't know if its correct to place it in layoutSubviews, but I couldn't get it to work just by calling the gradient code directly, such as in viewDidLoad for example:

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)
}

Upvotes: 0

Views: 267

Answers (1)

vacawama
vacawama

Reputation: 154603

layoutSubviews() gets called multiple times, so your gradient is getting added repeatedly. layoutSubviews() is not really the place to be adding this gradient. The reason adding it in viewDidLoad() was not working for you is because the bounds of the view haven't been established yet. Go ahead and set up your gradient in viewDidLoad(). Keep the gradient as a property, and use viewDidLayoutSubviews() to update the frame.

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
    }
}

For a view that is a subclass of UIView, you'd handle it like this:

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
    }
}

Upvotes: 3

Related Questions