UIView 动画的两种编程方式

iOS  中的 UIView 动画编程其实还是很简单的,像 CSS3 一样,在给定的时间内完成状态连续性的变化呈现。比如背景色,Frame 大小,位移、翻转,特明度等。


以前我使用的编程方式都是用下面那样的三段式处理:
1[UIView beginAnimations:nil context: nil];
2[UIView setAnimationDuration:1.0];
3    
4//要动画改变的属性
5self.view.alpha = 0.0;
6self.view.frame = CGRectMake(10, 10, 50, 50);
7    
8[UIView commitAnimations];

那么被 beginAnimations 和  commitAnimations 框起来的代码就会让你产生动画效果,这种方式像是数据库中的事物编程一样。

还有另一种编程方式,使用代码块,对于常常书写 JS 代码的同志会比较适应,还是来个简单的代码片段:
1[UIView animateWithDuration:1.0
2                 animations:^{
3                     self.view.alpha = 0.0;
4                     self.view.frame = CGRectMake(10, 10, 50, 50);
5                 }];

对于不太复杂的动画,上面的写法很精练,因为只有一条语句,如果动画太过复杂了,写在这样一条语句中就会显得冗长了,对于代码调试没那么方便。

animateWithDuration 有三个重载方法:



比如我们用最后面那个重载方法,可以比 beginAnimations...commitAnimations 更轻松的实现动画完后执行的动作,如:
 1[UIView animateWithDuration:1.0
 2                      delay: 0.0
 3                    options: UIViewAnimationOptionCurveEaseIn
 4                 animations:^{
 5                     self.view.alpha = 0.0;
 6                     self.view.frame = CGRectMake(10, 10, 50, 50);
 7                 }
 8                 completion:^(BOOL finished){
 9                     NSLog(@"Do something after the animation.");
10                 }];

再回头看看 beginAnimations...commitAnimations 该如何实现上面同样的行为:
 1[UIView beginAnimations:nil context: nil];
 2[UIView setAnimationDuration:1.0];
 3    
 4[UIView setAnimationDelay:0.0];
 5[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
 6    
 7[UIView setAnimationDelegate:self];
 8[UIView setAnimationDidStopSelector:@selector(animationStopped)];
 9   
10self.view.alpha = 0.0;
11self.view.frame = CGRectMake(10, 10, 50, 50);
12    
13[UIView commitAnimations];

还要给当前类加一个方法 animationStopped:
1-(void) animationStopped {
2    NSLog(@"Do something after the animation.");
3}

代码是多些,但是 beginAnimations...commitAnimations 编程方式是全能的,而 animateWithDuration 是有局限性的,因为它的目的就是让编写代码更简洁。在 animateWithDuration 中只提供了 completion 代码块,意即在动画完成后执行的动作,而要达成

[UIView setAnimationWillStartSelector:@selector(animationWillStart)]

这样的在动画即将启动之前的动作却是无能为力,还有些动画设置也是 animateWithDuration 做不到。所以一旦你先前用 animateWithDuration  实现的动画方式要增加稍复杂的功能而不得不用 beginAnimations...commitAnimations 来改写时,付出就大了。

该用哪种方式,只能自己斟酌吧。

关于 UIView 的动画请参考官方文档:Animations 永久链接 https://yanbin.blog/uiview-animation-programming/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。