【问题标题】:Find out the animation duration of the current animation block找出当前动画块的动画时长
【发布时间】:2012-04-05 07:51:30
【问题描述】:

在 UIView 动画块中,有没有办法获取当前动画的时长?

[UIView animateWithDuration:1.0 animations:^{
    // float duration = ?
}];

【问题讨论】:

  • 我不确定我理解你的意思,动画持续时间不是1.0吗?
  • 是的,但我在块内使用需要知道持续时间的组件,并且我不想将持续时间作为变量传递
  • 好问题 +1 抱歉帮不上忙。
  • 我认为没有变量是不可能的……有没有特别的原因不使用它?

标签: iphone animation uiview uiviewanimation


【解决方案1】:

如果您的目标是iOS 9.0 或更高版本,那么您正在寻找UIView 的类属性,称为inheritedAnimationDuration

用法:

let currentAnimationDuration = UIView.inheritedAnimationDuration

来自 Apple 文档

总结

返回当前动画的继承时长。

讨论

如果在 UIView 动画块中调用此方法,则仅返回非零值。

【讨论】:

  • 感谢它节省了我很多时间
【解决方案2】:

TL;DR:使用 CALayer -actionForKey:,而不是 -animationForKey:

@Dimitri Bouniol 从动画块内受影响的设置器调用时,我的答案对我不起作用。据我了解,原因是 UIView 的动画系统在开始实际动画之前设置状态(并在开始实际动画之前调用设置器)。对我有用的是在图层上调用类似的 -actionForKey: 方法。返回的操作确实设置了适当的持续时间,并且可以在他的答案中使用。

CAAnimation *animation = (CAAnimation *)[self.layer actionForKey@"position"]; // or property of interest

[CATransaction begin];
[CATransaction setAnimationDuration:animation.duration];
[CATransaction setAnimationTimingFunction:animation.timingFunction];

// CALayer animation here

[CATransaction commit];

【讨论】:

  • 在 iOS 11 中不起作用。actionForKey: 返回一个符合CAAction 协议但不是CAAnimation_UIViewAdditiveAnimationAction。所以timingFunction 属性不存在。 @Dimitri Bouniol 的回答对我有用。
【解决方案3】:

[CATransaction animationDuration] 就是你要找的东西

【讨论】:

  • 不幸的是,这不起作用,UIView 动画块显然不能直接与 CATransaction 一起使用。
【解决方案4】:

既然你在使用块,为什么不直接用它来捕获一个变量呢?

CGFloat duration = 1.0;
[UIView animateWithDuration:duration animations:^{ 
    CGFloat theDuration = duration; 
}];

【讨论】:

  • 同意。我们已经通过了持续时间,那么我们为什么要为此找到另一种方法。
【解决方案5】:

您可以很容易地获得当前动画。比如设置CATransaction:

CAAnimation *animation = [self.layer animationForKey:self.layer.animationKeys.firstObject];
[CATransaction begin];
[CATransaction setAnimationDuration:animation.duration];
[CATransaction setAnimationTimingFunction:animation.timingFunction];

// CALayer animation here

[CATransaction commit];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2011-11-27
    相关资源
    最近更新 更多