无法向 UIViewController 中的 UIImageView 添加渐变



UICollectionViewCell中,我向UIImageView添加渐变,如下所示:

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

我想做同样的事情,但UIViewController,到目前为止,我只能让它在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)
}
}

你可以用viewDidLayoutSubviews来调用它

最新更新