无法将渐变添加到 UIViewController 中的 UIImageView
Failing to add a gradient to a UIImageView in a UIViewController
在 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
中调用
在 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