Animate with springs!

Today I was having a look at some of the different UIView animation block methods and I noticed one that I'd never seen before. I read the docs and it is an amazing little function added for iOS 7.

The function (which is a bit of a mouthful as usual) is...

[UIView animateWithDuration:(CGFloat)duration
                      delay:(CGFloat)delay
     usingSpringWithDamping:(CGFloat)damping
      initialSpringVelocity:(CGFloat)velocity
                    options:(UIviewAnimationOptions)options
                 animations:^() (animations)
                 completion:^(BOOL finished) (completion)]

Like I said, it's a bit if a mouthful.

I haven't fully explored what is possible with this yet but from my first couple if attempts I was able to get some very effective UI animations that would have taken a lot of messing around using the standard block animations.

The two new parameters are fairly self explanatory but just to be certain...

usingSpringWithDamping
This is a float between 0 and 1. It affects how "strong" the spring is. A value of 1 will not oscillate at all. It will slow down until reaching the target value. A value of 0 is the opposite, the spring will oscillate infinitely. Now, I'm not sure how this works given the time constraint but I'll have a mess around in a bit.

initialSpringVelocity
This is also a float and is a relative value. The actual velocity unit is "total distance of the animation per second". I.e. If your animation has a total change of 100 points then a value of 1 will set the initial velocity at 100 points per second in the direction of the animation.
This last bit is quite important. The polarity of the velocity is not up or down but it is relative to the direction of the animation change. If you give it a negative number then your animation will start by "popping" in the opposite direction before springing back.

A quick note
I talk about "direction" in this blog but again that's not to say that this can only be used to animate changes in position. The spring essentially maps to a custom animation curve. This can be used for rotation, scale, transformation, anything that a standard animation can be used for.

Have fun messing around with it.

A quick video of something I made using the animate with springs API.

3 Comments

  1. oliverfoggin

    Hi, the reverse animation was a pain to get right. I used the same animate with spring damping method but spent ages tweaking the settings.

    I haven't got the exact parameters at but I used an initial velocity of less than zero to get the "pop" downwards.

    I'll get the exact numbers but that should help for now.

Leave a Reply

Your email address will not be published. Required fields are marked *