【问题标题】:Failing to add a gradient to a UIImageView in a UIViewController无法在 UIViewController 中向 UIImageView 添加渐变
【发布时间】:2020-02-08 22:05:50
【问题描述】:

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

【问题讨论】:

  • 显示你的代码,它适用于UIViewController

标签: ios swift cagradientlayer


【解决方案1】:

您可以拨打viewDidLayoutSubviews

【讨论】:

  • UIViewController的哪个方法?
  • 在 ViewDidLayoutSubviews 中
  • 我还得把if语句去掉,不然不行。
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
相关资源
最近更新 更多