layoutSubviews()
gets called multiple times, so your gradient is getting added repeatedly.
layoutSubviews()
is not really the place to be adding this gradient. The reason adding it in viewDidLoad()
was not working for you is because the bounds
of the view haven't been established yet. Go ahead and set up your gradient in viewDidLoad()
. Keep the gradient
as a property, and use viewDidLayoutSubviews()
to update the frame.
class ViewController: UIViewController {
let gradientLayer = CAGradientLayer()
override func viewDidLoad() {
super.viewDidLoad()
gradientLayer.type = .axial
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = .init(x: 0, y: 1)
gradientLayer.zPosition = 1
gradientLayer.opacity = 0.5
view.layer.addSublayer(gradientLayer)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradientLayer.frame = view.bounds
}
}
For a view that is a subclass of UIView
, you'd handle it like this:
class MyView: UIView {
let gradientLayer = CAGradientLayer()
override init(frame: CGRect) {
super.init(frame: frame)
addGradient()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addGradient()
}
func addGradient() {
gradientLayer.type = .axial
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = .init(x: 0, y: 1)
gradientLayer.zPosition = 1
gradientLayer.opacity = 0.5
layer.addSublayer(gradientLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…