1

I'm new to xcode and I am placing a gradient layer over a button and it is not filling the whole width. I'm not sure what I'm doing wrong. My code is here and screenshot of how it is rendering.

let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.btnSavePhoto.bounds
let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef
let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]
self.btnSavePhoto.layer.addSublayer(gradientLayer)

enter image description here

jessica mele
  • 417
  • 5
  • 20

1 Answers1

2

It seems like your button changes it's size later on (due to autoresizing masks or constraints), but the gradientLayer stays of the original (smaller) size. It is caused by the fact that layers don't resize automatically. You can create a custom UIButton subclass that would update the sizing of a custom layer in layoutSubviews method. Or you can create a custom layer subclass, although it would also require to create a UIButton subclass, as described in this question: CALayers didn't get resized on its UIView's bounds change. Why?

Community
  • 1
  • 1
hybridcattt
  • 3,001
  • 20
  • 37
  • thank you for your answer. How would I go about creating a custom UIButton subclass that would update the sizing of a custom layer in layoutSubviews method? – jessica mele Aug 24 '16 at 17:01
  • Create a subclass of UIButton where in the initWithFrame method you would create your gradient layer and store it to a strong property (var), and also add it as a sublayer. (same as you do now) Then override layoutSubviews() method, where you would call super.layoutSubviews() and resize your layer: self.gradientLayer.frame = self.bounds. Sorry I can't post actual code that you could immediately use, but I can do it later if you still need help :) – hybridcattt Aug 24 '16 at 17:06
  • if you could and have the time that would be great, I can only really make cosmetic changes at this point and am a little lost when it comes to the programming side. – jessica mele Aug 24 '16 at 17:20