1

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:

  1. white to black to white
  2. white to black to white
  3. white to black to white
  4. white to black to white

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Roi Mulia
  • 5,626
  • 11
  • 54
  • 105

1 Answers1

1

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)
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • no idea why it crushes, Thread 1 : signal SIGABRT , i think i havent implement it good , i just copy pasted the function and called it in a button action like you did, any reason why it crushed? – Roi Mulia Nov 01 '14 at 16:02
  • @roimulia that may be because you're you're calling UIView methods in the callback of the previous animation, I'm new to this but... I think if the animations run on a background thread, that may cause problems. Try wrapping the code in a dispatch to the main queue – DiogoNeves Sep 02 '15 at 11:37
  • Thanks Diogo! long time since i posted this answer , figure it already while ago - NEVER change UI on background theards , only main :) – Roi Mulia Sep 03 '15 at 07:59