Looping background colours of UIView

An app we’re working on required the background of a UIView to animate through a number of colours in a loop and we wanted to share the solution with you.

Create an array of as many colours as you want and set-up your array index in your view (we did it in viewDidLoad but it could be anywhere)

self.backgroundColours = [NSArray arrayWithObjects:
[UIColor colorWithRed:64/255.0 green:70/255.0 blue:69/255.0 alpha:1],
[UIColor colorWithRed:221/255.0 green:71/255.0 blue:77/255.0 alpha:1],
[UIColor colorWithRed:221/255.0 green:77/255.0 blue:117/255.0 alpha:1],
[UIColor colorWithRed:227/255.0 green:124/255.0 blue:168/255.0 alpha:1],
[UIColor colorWithRed:228/255.0 green:136/255.0 blue:115/255.0 alpha:1], nil];

self.backgroundLoop = 0;

Then create an animateWithDuration function that calls itself:

- (void) animateBackgroundColour
{

	if (self.backgroundLoop < self.backgroundColours.count - 1)
	{
		self.backgroundLoop ++;
	}
	else
	{
		self.backgroundLoop = 0;
	}

	[UIView animateWithDuration:4 delay:0.5 options:UIViewAnimationOptionAllowUserInteraction
					 animations:^(void)
					{
						self.backgroundView.backgroundColor = [self.backgroundColours objectAtIndex:self.backgroundLoop];
					}
					 completion:^(BOOL finished) {
						 if(finished)
						 {
							[self animateBackgroundColour];
						 }
	}];
}

And that’s it. The UIViewAnimationOptionAllowUserInteraction is important so that input can be used for the rest of the interface as by default when an animation is playing interaction is disabled. You can include as many colours as you require. If you need to stop the animation then either call:

[myView.layer removeAllAnimations];

Which will remove all of the animations currently playing, which is fine if this is the only one. Alternatively you can start a new , very short, animation on the background colour that returns it to its original (or new) state. This will override the looping animation nicely. Here’s a few tricks people have used to do this very thing, you may find one or more works for your situation.

Comments are closed.