Animations can add a lot of magic to your application. They can be used to impress your users with great effects and give important user feedback to encourage a positive behavior. Creating animations using the Apple supplied UIView API is quite easy and by using UIViewAnimationOptions correctly, you can either create or improve the animations in your app.
You might be familiar with the UIView animation API. However one of the lesser used parts of this API is including the UIViewAnimationOptions. This allows you to improve the realism of your animations. These options change the animations time over progress ratio. By doing this, objects accelerate or decelerate whilst animating. This is important because, in the real world, objects do not start and stop instantly and do require time to speed up and slow down. Here is a diagram which shows two of the options. EaseIn starts the animation slowly and accelerates the progress, while EaseOut starts the animation quickly and decelerates the progress.
Start off with a simple single page application template. Set yourself up three cars (all at the same Y position origin) and a race button above the vehicles. The labels above the vehicles and the red finish line are optional.
Then we want to create the necessary outlets for the cars and their top constraints. It is very important that the outlets to the constraints are correct, as these are the constraints that will be manipulated in the animation block.
Now we should be ready to start animating our outlets. I have created some constants within the UIViewController, to help simplify the animation code. You can do the same if you wish.
Our animation code is going to sit entirely within our IBAction method. It’s a good idea to keep your IBActions as short as possible. However, because this is a simple demo I will make an exception. When we press the “Race” button, the top constraints for the cars will be modified to the position needed to help them cross the finish line. The cars will be animated for the same length of time and cover the same distance, but each in a different way according to their UIViewAnimationOptions.
Modify your constraint constant and call layoutIfNeeded inside the animation block, this will use Auto-Layout to perform the animation. Note that it is best practice to call layoutIfNeeded function before the animation block as well to ensure that all pending layout operations have been completed.
Here is the full source code for the project: