UIView+EasingFunctions
This is a category on UIView
that allows to attach custom easing functions to animatable UIView
properties.
UIView+EasingFunctions
works great with AHEasing, a library of easing functions. The library contains almost every easing function you might ever need.
Of course you can write your own easing functions as well.
Easing functions?
Easing functions specify the rate of change of a parameter over time. Objects in real life donโt just start and stop instantly, and almost never move at a constant speed. When we open a drawer, we first move it quickly, and slow it down as it comes out. Drop something on the floor, and it will first accelerate downwards, and then bounce back up after hitting the floor.
from easings.net (you should probably check the site, it does a great job explaining and illustrating various easing functions)
Installation
###Cocoapods###
Cocoapods is an Objective-C library manager.
Adding UIView+EasingFunctions to your project using Cocoapods is as easy as adding the following line to your Podfile
:
pod 'UIView+EasingFunctions'
UIView+EasingFunctions podspec automatically adds AHEasing to the project as well. If that's not something you want, use pod 'UIView+EasingFunctions/Bare'
instead.
###Manually###
- Download and unarchive.
- Drag and drop
UIView+EasingFunctions
subfolder, containingUIView+EasingFunctions.h
and.m
files into your Xcode project's Project Navigator (left pane), click Finish. - Add
QuartzCore.framework
to your project'sLink Binary With Libraries
build phase.
Usage
Let's say you want to make a bouncy frame
animation:
#import <UIView+EasingFunctions/UIView+EasingFunctions.h>
#import <AHEasing/easing.h>
/* ... */
[view setEasingFunction:BounceEaseOut forKeyPath:@"frame"];
That's it. Now any frame
animation of this view will use BounceEaseOut
easing function (defined in AHEasing/easing.h
):
[UIView animateWithDuration:.5 animations:^{
view.frame = CGRectMake(10, 110, 100, 32);
}];
What if you only want one specific animation block to be affected? Use the completion block to remove the easing function:
[UIView animateWithDuration:.6 animations:^{
[view setEasingFunction:ElasticEaseOut forKeyPath:@"center"];
view.center = CGPointMake(160, 415);
} completion:^(BOOL finished) {
[view removeEasingFunctionForKeyPath:@"center"];
}];
There's a sample app project available (make sure to open .xcworkspace
file, not the .xcodeproj
).
What properties are supported?
All animatable properties of UIView
.
Gotchas
Animating backgroundColor
between two colors in different color spaces (including pattern images) won't do any good.
How it works
It swizzles addAnimation:forKey:
of the view's backing CALayer
.
Acknowledgement
The entire idea of hijacking the backing layer's addAnimation:forKey:
comes from this blog post by Evadne Wu.