不要嵌套Animation Blocks

当需要为UIView添加动画,而动画是多个的时候,就会出现completion block嵌套,如下:

               }];
            }];
        }];
    }];
}];

在iOS7中,有一个方法可以优雅地解决以上问题:

animateKeyFramesWithDuration: delay: options: animations: completion:

在这个completion block中,我们可以用一下方法添加另一个动画效果:

addKeyframeWithRelativeStartTime: relativeDuration: animations:

addKeyframe...的这个方法就可以避免在一个completion block中创建一个新的动画.

以下的动画实现了UIView上下来回转动:

[UIView animateKeyframesWithDuration:5.0 delay:0.0 options:0 animations:^{
        [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
            self.verticalPosition.constant = 200.0;
            [self.view layoutIfNeeded];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.25 animations:^{
            self.verticalPosition.constant = 50.0;
            [self.view layoutIfNeeded];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.75 relativeDuration:0.125 animations:^{
            self.verticalPosition.constant = 200.0;
            [self.view layoutIfNeeded];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.875 relativeDuration:0.0625 animations:^{
            self.verticalPosition.constant = 50.0;
            [self.view layoutIfNeeded];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.9375 relativeDuration:0.03125 animations:^{
            self.verticalPosition.constant = 200.0;
            [self.view layoutIfNeeded];
        }];
        [UIView addKeyframeWithRelativeStartTime:0.96875 relativeDuration:0.015625 animations:^{
            self.verticalPosition.constant = 50.0;
            [self.view layoutIfNeeded];
        }];
    } completion:nil];

原文连接 Stop nesting Animation Block

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 10,514评论 5 13
  • 在iOS实际开发中常用的动画无非是以下四种:UIView动画,核心动画,帧动画,自定义转场动画。 1.UIView...
    请叫我周小帅阅读 8,359评论 1 23
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 12,707评论 6 30
  • - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *...
    七里田间的守望者阅读 5,262评论 0 4
  • 前言 本文只要描述了iOS中的Core Animation(核心动画:隐式动画、显示动画)、贝塞尔曲线、UIVie...
    GitHubPorter阅读 8,989评论 7 11