I currently have a single gradient color background (see below), but I want to gradually change the colors to shades that I will pre-define in an array and have it loop through. How can I achieve this?
var colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
var colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor
func configureGradientBackground(colors:CGColor...){
let gradient: CAGradientLayer = CAGradientLayer()
let maxWidth = max(self.view.bounds.size.height,self.view.bounds.size.width)
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
let squareFrame = CGRect(origin: self.view.bounds.origin, size: CGSize(width: maxWidth, height: maxWidth * 0.935))
gradient.frame = squareFrame
gradient.colors = colors
view.layer.insertSublayer(gradient, at: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
configureGradientBackground(colors: colorTop, colorBottom)
}
You could have a variable in your
viewDidLoad
that is an int that keeps track of the index of the array that contains all your colors. For example, 0 is your first color, 1 is your second and so on. Then in your infinite while loop (also in theviewDidLoad
), you can write:Then you can increment the tracker by one at the end and then check your if your tracker is past the size of your array (for example, you only have 11 colors).