Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the way to go is to represent what you want to happen in each animation parametrically (which in this case is just a color), and then keep those params in an array. The array is like your animation to-do list:</p> <pre><code>@property(strong, nonatomic) NSArray *animationTodo; </code></pre> <p>We also need to keep track of where we are in the list. Use a boxed (NS) number so we can represent "don't animate" as a nil, distinct from index zero:</p> <pre><code>@property(strong, nonatomic) NSNumber *animationIndex; </code></pre> <p>The array is initialized with colors:</p> <pre><code>self.animationTodo = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], ... nil]; </code></pre> <p>Now the animation can be compressed to a single method:</p> <pre><code>- (void)animate { if (!animationIndex) return; NSInteger index = [animationIndex intValue]; [UIView animateWithDuration:3.0 animations:^{ self.view.backgroundColor = [animationToDo objectAtIndex:index]; } completion:^(BOOL finished) { NSInteger nextIndex = (index==self.animationTodo.count-1)? 0 : index+1; // advance index in a ring self.animationIndex = [NSNumber numberWithInt:nextIndex]; // schedule the next one in 3s [self performSelector:@selector(animate) withObject:nil afterDelay:3.0]; }]; } </code></pre> <p>Perform selector let's you state the delay and also has the positive effect of not winding up the stack each time you start the next animation.</p> <p>Stopping is simple now, too. Do this before the view disappears and any other time you wish to stop.</p> <pre><code>- (void)stopAnimating { self.animationIndex = nil; [NSObject cancelPreviousPerformRequestsWithTarget:self]; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload