Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the animation duration of the current animation block

Inside a UIView animation block, is there a way to get the current animation's duration?

[UIView animateWithDuration:1.0 animations:^{
    // float duration = ?
}];
like image 776
adamsiton Avatar asked Apr 05 '12 07:04

adamsiton


People also ask

What is animation duration?

The time that an animation takes to complete one cycle. This may be specified in either seconds ( s ) or milliseconds ( ms ).

Can you set the duration of an animation?

To run your animation effect at a faster or slower pace, change the Duration setting. On the slide, click the text or object that contains the animation effect that you want to set the speed for. On the Animations tab, in the Duration box, enter the number of seconds that you want the effect to run.

What is the default animation time?

Duration: You can specify the duration of an animation. The default length is 300 ms.

Which of the following rules will set the time duration of an animation to 5 seconds?

Possible Values For example, a value of 5s would result in the animation taking 5 seconds to complete. By default the value is 0s , meaning that the animation cycle is immediate (i.e. you would not see any animation).


3 Answers

If you are targeting iOS 9.0 or later, then you are looking for a class property of UIView, called inheritedAnimationDuration.

Usage:

let currentAnimationDuration = UIView.inheritedAnimationDuration

From Apple docs:

Summary

Returns the inherited duration of the current animation.

Discussion

This method only returns a non-zero value if called within a UIView animation block.

like image 197
Dennis Pashkov Avatar answered Nov 10 '22 06:11

Dennis Pashkov


TL;DR: use CALayer -actionForKey:, not -animationForKey:

@Dimitri Bouniol 's answer didn't work for me when called from an an affected setter inside an animation block. The reason, from my understanding, is that UIView's animation system sets up state before starting the actual animation (and calls setters before starting the actual animation). What worked for me though was calling the similar -actionForKey: method on the layer. The action returned did have the proper duration set, and can be used as it is in his answer.

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];
like image 44
Chris Conover Avatar answered Nov 10 '22 07:11

Chris Conover


[CATransaction animationDuration] is what you're looking for

like image 1
Nick Dowell Avatar answered Nov 10 '22 06:11

Nick Dowell