I have a simple CustomView
. I have a CAGradientLayer
that I am adding to the layer
.
@IBDesignable
class CustomView: UIView {
override init (frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
setupView()
}
private func setupView() {
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
layer.insertSublayer(gradient, at: 0)
}
}
Below is the Storyboard
setup
Below is the result in portrait on iPad, which is fine.
When the device orientation is changed, the layer of the CustomView
is protruded from its bounds.
When I checked the view hierarchy in Xcode, the frame of the CustomView
is adjusted accordingly, but, it is the layer which is protruding. To cross check, I removed all codes in setupView
and set only a background colour, on orientation change, CustomView
is adjusted as expected. But, why does it happen for layers?
CodePudding user response:
You are inserting a new layer each time when layoutSubviews
method call. That means it shows the line of the first layer.
Just update the frame from layoutSubviews
and call setup method from awakeFromNib
.
class CustomView: UIView {
private let gradient = CAGradientLayer()
override init (frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = bounds
}
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
private func setupView() {
gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
layer.insertSublayer(gradient, at: 0)
}
}