在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
中调用它>