iOS动画iOS绘图与动画

不要嵌套Animation Blocks

2014-04-26  本文已影响400人  不是谢志伟

当需要为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

上一篇 下一篇

猜你喜欢

热点阅读