Y
Y
Yapryntsew2018-11-05 17:26:08
iOS
Yapryntsew, 2018-11-05 17:26:08

How to dynamically update CAGradientLayer dimensions?

I have my own subclass of UIButton to which I wanted to add a gradient as a background. I have created an extension for UIView and using this method I am adding a gradient layer. With this approach, the dimensions of the layer do not change when the screen is rotated, or when using .contentEdgeInsets. Is it possible to fix this behavior or is there another way to implement the current task?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ManWithBear, 2018-11-05
@Yapryntsew

Resizing CALayer'a lies entirely with its user.
Therefore, you need to change the position / size of the layer every time you change the frame of the view.
Example:

class MyView: UIView {
    let gradient: CALayer 
    ...
    override func layoutSubviews() {
        super.layoutSubviews()
        gradient.frame = self.bounds
    }
}

If you really really want through the extension, then something like this:
private var gradientPropertyKey: UInt8 = 0
extension UIView {
    func addNiceGradient() {
        let gradient =  < тут ваш слой >
        layer.addSublayer(gradient)
        let observation = layer.observe(\.bounds) { [weak gradient] layer, _ in
            gradient?.frame = layer.bounds
        }
        objc_setAssociatedObject(self, &gradientPropertyKey, observation, .OBJC_ASSOCIATION_RETAIN)
    }
}

But it will work worse, and are you sure that you want to climb into the ObjC Runtime for no reason?

D
Dima Grib, 2018-11-05
@YeahGarage

And if you put a larger fill area at the bottom of the gradient layer, and add masksToBounds = true at the button or under the layer?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question