Changing UIView background color using an animation

Kex picture Kex · May 21, 2015 · Viewed 9k times · Source

I want to change my UIView background color with a transition animation. For example, if the view is red and I change it to blue. The blue color will slide up from the bottom of the screen to the top and fill the whole screen. I was thinking of doing this by making a UIView of identical size with the desired color and then animating it from off screen up to the top. This doesn't seem like a very elegant way to do it though. Is there any better way of doing this? Any points would be really appreciated. Thanks!

Answer

Lucas Huang picture Lucas Huang · May 21, 2015

Try this:

CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height);
layer.backgroundColor = [UIColor blueColor].CGColor;
[self.view.layer addSublayer:layer];

CABasicAnimation *animation = [CABasicAnimation animation];
animation.keyPath = @"position.y";
animation.byValue = @(-self.view.bounds.size.height);
animation.duration = 1;

animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;

[layer addAnimation:animation forKey:@"Splash"];

You can try this out:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp
                       forView:self.view cache:NO];
self.view.layer.backgroundColor = [UIColor blueColor].CGColor;
[UIView commitAnimations];

I also have another suggestion that make the transition smooth:

[UIView animateWithDuration:2.0 animations:^{
    self.view.layer.backgroundColor = [UIColor blueColor].CGColor;
} completion:nil];