I'm trying to animate the background of my view for several times. For example(of course it's need to be dynamic solution) for 4 seconds, each second it will animate from white to black. what we expect: second:
I tried using for and even delay(dispatch delay),and it will run it only 1 time and than stop. This is what I tried.
for var index = 0; index < 3; ++index {
UIView.animateWithDuration(0.33333, delay: 0.333333, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
println(elapsedTime)
self.view.backgroundColor = UIColor.blackColor()
}) { (completed : (Bool)) -> Void in
UIView.animateWithDuration(0.333333, animations: { () -> Void in
self.view.backgroundColor = UIColor.whiteColor()
})
}
}
Any suggestions on how I can run these commands, wait until they complete and than run them again?
With that for
loop, you're essentially setting up all four animations to run at the same time. If you make that animation code a function, you can call it recursively from the completion block for your white animation:
func animateBackground(times: Int) {
if times == 0 { return }
let blackAnimation = { self.view.backgroundColor = UIColor.blackColor() }
let whiteAnimation = { self.view.backgroundColor = UIColor.whiteColor() }
UIView.animateWithDuration(0.33333, delay: 0.333333, options: UIViewAnimationOptions.CurveEaseIn, animations: blackAnimation) {
completedBlack in // completion block 1
UIView.animateWithDuration(0.333333, animations: whiteAnimation) {
completedWhite in // completion block 2
self.animateBackground(times - 1)
}
}
}
And the initial call looks like:
animateBackground(4)