UIView动画块:如果持续时间为0,是否与没有动画相同?

hzx*_*zxu 15 objective-c uiview uiviewanimation ios

我需要处理一个案例,你可以做一些有或没有动画的事情,而不是:

if (animation)
{
    [UIView animateWithBlock:^(){...}];
}
else
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想要做:

[UIView animateWithBlock:^(){...} duration:(animation ? duration : 0)]
Run Code Online (Sandbox Code Playgroud)

但不确定它是否有效,即使它确实如此,是否有使用它的开销而不是直接更改视图?

谢谢

Dan*_*cía 28

在这种情况下我做的是创建一个包含我想要制作的所有动画的块.然后执行一个UIView动画,将动画块作为参数传递,或直接调用该块,无论我是否想要动画.像这样的东西:

void (^animationBlock)();
animationBlock=^{
      // Your animation code goes here
};
if (animated) {
    [UIView animateWithDuration:0.3 animations:animationBlock completion:^(BOOL finished) {

    }];
}else{
    animationBlock();
}
Run Code Online (Sandbox Code Playgroud)

这样可以避免开销


che*_*bur 19

根据Apple文档:

如果动画的持续时间为0,则在下一个运行循环周期开始时执行该块.

  • @hzxu 正是如此。效果与调用 `[self PerformSelector:@selector(animate) afterDelay:0]` 相同 (2认同)

Pap*_*lls 8

是的,由于持续时间为零,过渡将有效地瞬间完成.

  • 我用iOS 7.1.1 5S测试了它,差别很大; 为视图设置一个随机帧10k次,使用^ animateWithBlock:^和0.05秒,直接调用该块.但是,如果您只为一些用户交互执行少量动画调用,则差异无关紧要.请注意,Apple可能会在未来改变行为并优化此边缘情况. (11认同)
  • 它有任何开销吗?即.`[UIView animateWithBlock:^(){self.view.frame = newFrame} withDuration:0]`vs`self.view.frame = newFrame`? (3认同)
  • 这个答案不再准确。设置为 0 不会立即发生,它将花费接近 0.25 秒的默认时间段。 (3认同)