1

I'm adding a gradient to a view and it's cutting off the width on one side.

My code for adding the gradient is

let gradientLayer = CAGradientLayer()
gradientLayer.frame = fadeView.frame
gradientLayer.colors = [UIColor.mainColor().cgColor, UIColor.white.cgColor]

fadeView.layer.addSublayer(gradientLayer)

The fadeView is inside of a vertical stackView, inside of a view inside of a scrollView, all of which have horizontal constraints on the left and right of 0, not constraining to margins.

The frame width for the fadeView (and all other views other than the main view) is 320, but that might just be because of the device I'm testing on. The width of the screen is actually 375.

What's causing it to cut off like this?

Cody Harness
  • 1,116
  • 3
  • 18
  • 37
  • have you tried `gradientLayer.frame = fadeView.bounds`? – Malik Aug 18 '17 at 02:27
  • @Malik same results. I forgot I did that one first. – Cody Harness Aug 18 '17 at 02:27
  • is this code in `viewDidLoad` or `viewWillAppear`? – Malik Aug 18 '17 at 02:29
  • It's called from `viewDidLoad`. – Cody Harness Aug 18 '17 at 02:29
  • Try moving it to `viewDidAppear` – Malik Aug 18 '17 at 02:29
  • If you're adding the gradient in the custom UIView class, you need to set the frame in the drawRect method. It seems that your frame was not updated in the time you're setting it to the gradient layer – Woof Aug 18 '17 at 02:30
  • That's what I figure as well... that's why I asked him to move it to `viewDidAppear` to confirm that theory – Malik Aug 18 '17 at 02:31
  • Moving it to `viewDidAppear` did take care of the sizing, but now there is a noticable delay before it appears. Is this because my code in `viewDidLoad` takes too much processing, or because `viewDidAppear` won't be called until the layout appears? – Cody Harness Aug 18 '17 at 02:37
  • 3
    You should not add the whole implementation to the viewDidAppear. Make an instance of the gradient outside the methods. Add it as a sub view inside the viewDidLoad() (also set colors here) and set it's frame in the view controller viewWillAppear method or if it will not make a fit, then in the viewDidLayoutSubviews() method – Woof Aug 18 '17 at 02:57
  • @Woof Thanks, that took care of it! – Cody Harness Aug 18 '17 at 03:34

1 Answers1

1

Change this

 gradientLayer.frame = fadeView.frame

to

gradientLayer.frame = fadeView.bounds
Abdul Waheed
  • 863
  • 8
  • 14