简体   繁体   中英

CAGradientLayer isn't spanning the whole width of my button - xcode

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)

在此处输入图片说明

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM