Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing UIView background color using an animation

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!

like image 731
Kex Avatar asked Dec 08 '22 03:12

Kex


1 Answers

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];
like image 159
Lucas Huang Avatar answered Dec 22 '22 02:12

Lucas Huang