ios - 无法在 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)
}
}
解决方案
你可以调用它viewDidLayoutSubviews
推荐阅读
- bootstrap-4 - 如何在引导程序 4 表中使列可排序
- c# - Observable 字典中的集合更改事件
- swift - 当行包含按钮时禁用表单行选择
- javascript - 名称列表取决于对象中的另一个字段
- regex - 正则表达式:使用 RE2 语法查找双字
- android - Google Play 控制台:丢失了上传 APK 所需的上传密钥
- prolog - 如何编写一个计算总工资且小于一个值的 prolog 查询?
- sql - SQL如何按字母顺序对带有数字的文本进行排序,然后按数字排序
- java - 如何在每个线程的基础上限制 Java 的堆栈大小?
- x509certificate - XML 签名和 TLS 的 X.509 证书