I want to apply view gradient color but always failed.
I want to apply gradient view like this image:

I try with this code:
func gradientColor(topLeft: UIColor, bottomRight: UIColor) {
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: self.mainView.bounds.width, height: self.mainView.bounds.height)
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.colors = [topLeft.cgColor, bottomRight.cgColor]
self.mainView.layer.addSublayer(gradient)
}
but result as empty no color (color did not show) at all if I called like this:
gradientColor(topLeft: UIColor.style.negativeGradient, bottomRight: UIColor.style.negative)
What is the correct code to generate gradient view like that image?
This approach commonly fails because it is called before the views have been laid-out, so
self.mainView.boundsis not valid.A much more reliable - and flexible - approach is to subclass
UIViewand have it do all the "background styling" automatically.Quick example class:
You are probably doing this:
so, instead, we can do this:
and we get this (for example):
We can add multiple instances, at various sizes:
and we can add subviews as we normally would:
and set / change colors if desired: