bruno
bruno

Reputation: 2169

Failing to add a gradient to a UIImageView in a UIViewController

In a UICollectionViewCell i'm adding a gradient to a UIImageView like this:

    override func layoutSubviews() {
        super.layoutSubviews()

        if thumbnailImageView.layer.sublayers?.first == nil {
            thumbnailImageView.addGradient(firstColor: .clear, secondColor: .black)
        }
    }

I want to do the same but in a UIViewController, so far I could only make it work on viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if thumbnailImageView.layer.sublayers?.first == nil {
        thumbnailImageView.addGradient(firstColor: .clear, secondColor: .black)
    }
}

I want to the UIImageView to have the gradient as soon as it appears like I did in UICollectionView. Do you know how can I do this?

extension UIView{

    func addGradient(firstColor: UIColor, secondColor: UIColor){
        clipsToBounds = true
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
        gradientLayer.frame = self.bounds
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 0, y: 1)
        self.layer.insertSublayer(gradientLayer, at: 0)
    }
}

Upvotes: 1

Views: 49

Answers (1)

Ramy Rizkalla
Ramy Rizkalla

Reputation: 264

You can call it in viewDidLayoutSubviews

Upvotes: 2

Related Questions