Fast loop background color animation

I want the background color of my iOS application to change between four colors in x seconds.

This is what I still do (it does exactly what I want when I specify only 2 colors)

I also need animation to run the loop endlessly.

ViewController.swift

UIView.animateWithDuration(X.0, animations: { // Color 1 self.view.backgroundColor = UIColor(rgba) // Color 2 self.view.backgroundColor = UIColor(rgba) // Color 3 self.view.backgroundColor = UIColor(rgba) // Color 4 self.view.backgroundColor = UIColor(rgba) }) 
+9
source share
3 answers

Try it:

 UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.backgroundColor = UIColor.blackColor() }) { (Bool) -> Void in UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.backgroundColor = UIColor.greenColor() }, completion: { (Bool) -> Void in UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.backgroundColor = UIColor.grayColor() }, completion: { (Bool) -> Void in UIView.animateWithDuration(1.0, animations: { () -> Void in self.view.backgroundColor = UIColor.redColor() }, completion:nil) }) }) } 

If you need continuous looping animation, try this:

 UIView.animate(withDuration: 2, delay: 0.0, options:[UIView.AnimationOptions.repeat, UIView.AnimationOptions.autoreverse], animations: { self.view.backgroundColor = UIColor.black self.view.backgroundColor = UIColor.green self.view.backgroundColor = UIColor.darkGray self.view.backgroundColor = UIColor.red }, completion: nil) 
+15
source

The code below helps maintain user interaction with the animated view. Random color generation (use if necessary).

 UIView.animateWithDuration(7, delay: 1, options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.Repeat, UIViewAnimationOptions.Autoreverse], animations: { self.yourView.backgroundColor = self.randomColor() self.yourView.backgroundColor = self.randomColor() }, completion:nil ) func randomColor() -> UIColor { let randomRed:CGFloat = CGFloat(drand48()) let randomGreen:CGFloat = CGFloat(drand48()) let randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } 
+3
source

You should use NSTimer :

 let timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "update", userInfo: nil, repeats: true) func update() { let nextCollor = getNextColor() UIView.animateWithDuration(X.0, animations: { self.view.backgroundColor = nextCollor }) } func getNextColor() -> UIColor { let currentColor = self.view.backgroundColor if currentColor == smaple1 { return UIColor.redColor() } else if currentColor == smaple2 { return UIColor.grayColor() } else { return UIColor.whiteColor() } } 

NSTimer.scheduledTimerWithTimeInterval runs your code every 5 seconds

PS: do not forget to make an invalid timer when you are done with it. Just call timer.invalidate() for it. Otherwise, you will fail.

+2
source

All Articles