首页 > 解决方案 > 无法在 UIViewController 中向 UIImageView 添加渐变

问题描述

在一个UICollectionViewCell我正在添加一个渐变到UIImageView这样的:

    override func layoutSubviews() {
        super.layoutSubviews()

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

我想做同样的事情,但在 aUIViewController中,到目前为止我只能让它工作viewDidAppear

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

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

我希望UIImageView在渐变看起来像我在UICollectionView. 你知道我该怎么做吗?

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

标签: iosswiftcagradientlayer

解决方案


你可以调用它viewDidLayoutSubviews


推荐阅读