Answer the question
In order to leave comments, you need to log in
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
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
}
}
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)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question