1

I'm trying to add a gradient to UIImageView.

viewDidLoad() {
    self.bookImageBig.sd_setImage(with: URL(string: self.book.image), placeholderImage: nil)
    self.bookImage.sd_setImage(with: URL(string: self.book.image), placeholderImage: nil)
    
    let view = UIView(frame: bookImageBig.frame)

    let gradient = CAGradientLayer()
    gradient.frame = view.frame
    gradient.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
    gradient.locations = [0.0, 1.0]
    view.layer.insertSublayer(gradient, at: 0)
    bookImageBig.addSubview(view)
    bookImageBig.bringSubviewToFront(view)
    

I'm trying to add a gradient to bookImageBig UIImageView.

However, the gradient only partially covers the image. 30px of the image is not covered by the gradient. The image was added to the story board and is being referenced in the view controller. Can someone please help?

swiftlearneer
  • 324
  • 4
  • 17
Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • Not only do you confuse frame with bounds, but you have concealed _when_ this code runs, which is crucial. If you run it in `viewDidLoad`, that’s bad. – matt Aug 10 '20 at 17:55
  • @matt I run it in viewDidLoad. Where should I run it? – Chris Hansen Aug 10 '20 at 17:58
  • After the first `viewDidLayoutSubviews`. Until then, the sizes are not right. Please read http://www.programmingios.net/premature-layout/ – matt Aug 10 '20 at 18:25
  • @matt I'm still confused. Where would you call it if it has to be called after viewDidLayoutSubviews and viewDidLayoutSubviews is called many times? – Chris Hansen Aug 10 '20 at 18:59
  • You do it in `viewDidLayoutSubviews` and you use a Bool instance property so you know this is the first time. – matt Aug 10 '20 at 19:03

1 Answers1

0

Instead of frame use bounds

gradient.frame = self.bookImageBig.bounds

For frame and bounds difference look at this post

Jawad Ali
  • 13,556
  • 3
  • 32
  • 49