Latest Posts:

iOS Animation Tutorial: Introduction to Easy Animation

While I worked on creating the iOS Animations by Tutorials video series and the three editions of the iOS Animations by Tutorials book I got a lot of ideas how the existing animation APIs can be improved – I felt they could be a bit more flexible and not as verbose.
That’s why after iOS Animations by Tutorials was released I started working and soon after released a lightweight animation library called Easy Animation.
This tutorial shows you how to use Easy Animation to build powerful view and layer animations quickly and easily. Easy Animation builds upon the solid foundation of Core Animation and gives you more mileage from the same APIs you’ve been always using.
Let’s get started! :]

What is Easy Animation?

Easy Animation extends the existing animateWithDuration(_:animations:) APIs and introduces a couple of new ones that follow the same naming pattern. And since Easy Animation is an open source library written in Swift, you can always peek inside and see how it works.
Just to give you a taste what Easy Animation is all about here’s an example: if you want to round the corners of a layer called myLayer in the span of 1.0 second with 0.5 seconds delay and ease the beginning of the animation you need all these lines of code:
let round = CABasicAnimation(keyPath: "cornerRadius")
round.fromValue = 0.0
round.toValue = 50.0
round.duration = 1.0
round.beginTime = CACurrentMediaTime() + 0.5
round.fillMode = kCAFillModeBackwards
round.timingFunction = CAMediaTimingFunction(name: 
  kCAMediaTimingFunctionEaseIn)
myLayer.addAnimation(round, key: nil)
myLayer.cornerRadius = 50.0
More to write means more possibility to introduce a bug and less time to experiment and polish. What Easy Animation allows you to do is to animate layers by using the standard UIKit animation methods.
To create precisely the same animation from the example above with Easy Animation, you only need to write this:
UIView.animateWithDuration(1.0, delay: 0.5, options: .CurveEaseIn, animations: {
  myLayer.cornerRadius = 50.0
}, completion: nil)
You can freely mix and match view and layer animations in the same animations block, use the completion blocks, create joint view-layer spring animations, and much more.
Without further ado let me show you few animation tricks you can do too with Easy Animation on your side.

Getting Started

For this tutorial, you’re going to make a little app called Random Pack List.
Download the RandomPackList Starter project, unzip it and open in Xcode. Select Main.storyboard and have a look inside.
The storyboard features a table view in the lower half of the initial view controller and a big + button in the upper half. The table view is already wired to the ViewController class so you can run up the project immediately check out what the app looks like:
image001
This packing app is more fun than other similar apps: when the app’s finished, the big plus button on top will add a random item to the packing list no matter what the user actually wants in their luggage! :]
image002

Installation

First and foremost, you need a copy of Easy Animation. Open the GitHub page for version 1.0:
https://github.com/icanzilb/EasyAnimation/releases/tag/1.0.0 and click the Source code (zip) button on the right to download the library source code.
Note: If you are familiar with CocoaPods you can get Easy Animation by adding pod ‘EasyAnimation’, ‘1.0.0’ to your Podfile. If you don’t know what CocoaPods is, the next chapter covers this in more detail.
Unzip the downloaded archive file and drag the sub-folder called EasyAnimation onto Xcode’s project navigator. In the dialog that pops up, check the Copy Items if Needed checkbox:
image003
Verify that you see the EasyAnimation folder and the files in your project like so:
image004
As soon as you’ve imported the files, you can start creating Easy Animation powered animations.
Note: If you use CocoaPods with frameworks enabled, don’t forget to import the framework by adding import EasyAnimation to the top of your source files.

Easy Layer Animations

First, you’ll add a playful rotation animation to the plus button. Open ViewController.swift and add the following to actionAddItem():
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: [], animations: {
  self.plusButton.transform = CGAffineTransformRotate(
    self.plusButton.transform, CGFloat(-M_PI_2))
}, completion: nil)
You’ve probably created animations just like this one before, so you probably aren’t terribly impressed. Nevertheless, run the project and make sure the button rotates playfully when you tap it:
image005
Next, you’ll animate the corner radius of the button’s layer. To liven up the animation, you’ll combine the rotation and the corner radius animations in a group so it looks like the button transforms into a circle as it rotates.
The usual approach for a combo animation like this would be to create a CAAnimationGroup and two separate CABasicAnimation instances: one to animate the layer’s transform property and the other its corner radius.
However, you have Easy Animation on your side. Simply add a second code of line in the animations closure to adjust the cornerRadius property from within the animations closure, just as you would for any view property:
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: [], animations: {
  self.plusButton.transform = CGAffineTransformRotate(
    self.plusButton.transform, CGFloat(-M_PI_2))
    self.plusButton.layer.cornerRadius = 62.5
}, completion: nil)
You’ve appended a single line, which simply sets the button’s corner radius to half the length of its side. This ought to round its corners to the point where the square becomes a circle.
Run the project again and check the resulting animation:
image006
The square smoothly animates into a circle, and not only that — it does so with a spring animation. The corners jiggle around a bit and then come to rest.
But… how? So far you’ve only used using CABasicAnimation and CASpringAnimation for layer animations. How can a view animation include a change to a layer property?
Easy Animation extends the existing UIKit animation APIs just a little and picks up any changes to animatable layer properties. It creates the respective animations automatically for you.
Even more – Easy Animation groups the view and layer animations together in a group so you don’t need to create a group yourself.
Add two more lines to the animations closure:
self.plusButton.layer.borderWidth = 2.0
self.plusButton.layer.borderColor = UIColor.grayColor().CGColor
These two lines animate the button border width and color respectively, just as you would for your view animations:
image007

Easy Animation Sequences

Now you’ll add a second animation that runs after the button has rotated to animate all changed properties back to their initial values.
So far you’ve probably used the completion block to chain animations in a sequence – but everyone who has tried to make a sequence of two or more animations knows that this approach leads to a very messy code.
Easy Animation introduces two new methods you can use to start a sequence of animations:
image008
animateAndChainWithDuration(_:delay:options:animations:completion:) lets you create an animation sequence by providing exactly the same initial parameters as you would for its original UIKit counterpart.
animateAndChainWithDuration(_:delay:usingSpringWithDamping:
initialSpringVelocity:options:animations:completion:)
 starts an animation chain with a spring animation as the first animation. It takes the same parameters as its original UIKit counterpart.
Starting an animation sequence is very simple – replace the method name in your code:
UIView.animateWithDuration(
with:
UIView.animateAndChainWithDuration(
Since the parameter count and names are the same, you can run and test your project right away. Nothing has changed though – you’ve created an animation sequence consisting of a single animation.
To add a second animation to the sequence, just place the cursor after the closing parenthesis of the first animation call, and type a “.” (a period or full stop); Xcode’s autocomplete feature will offer more animations for you to add:
image009
Choose the third animateWithDuration option from the suggested list – the one that lets you specify animation options — and set cornerRadius and borderWidth to their initial values. Use 0.15 seconds for the animation duration, 0.5 seconds of delay, and .CurveEaseOut for the options.
The completed code should now look like this:
UIView.animateAndChainWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.33, initialSpringVelocity: 0.0, options: [], animations: {
  self.plusButton.transform = CGAffineTransformRotate(
    self.plusButton.transform, CGFloat(-M_PI_2))
  self.plusButton.layer.cornerRadius = 62.5
  self.plusButton.layer.borderWidth = 2.0
  self.plusButton.layer.borderColor = 
    UIColor.grayColor().CGColor
}, completion: nil)
  .animateWithDuration(0.15, delay: 0.5, options: .CurveEaseOut, animations: {
  self.plusButton.layer.cornerRadius = 0.0
  self.plusButton.layer.borderWidth = 0.0
}, completion: nil)
Run your project again, tap the button and you’ll see it rotate, pause for half a second, then grow its corners back. At the end of the animation, the button will look the same as it did before you tapped it:
image010
You can tap the button again and again and it will run the animation sequence each time.
Note: To have a little fun at the button’s expense, add the .Repeat option to the second animation call. Run the project, tap the button and watch it go! :] Don’t forget to remove .Repeat option before continuing working trough the tutorial.

Completion closures

With Easy Animation, chaining animations is easy and doesn’t require the use of the completion parameter. However, they’re still available; you can use the completion closures to execute custom code at the end of the animation or in between the different animations of a sequence.
In this section, you are going to disable the button while it animates so the user cannot tap it again during the current animation.
Insert the following to the top of actionAddItem():
plusButton.enabled = false
Then replace the nil value of the completion block of the second animation with:
{_ in
  self.plusButton.enabled = true
}
This code will disable the button and re-enable it when the second animation in the sequence has finished running. If you tap repeatedly on the button it won’t react while it’s animating.
Finally replace the nil value of the completion parameter of the first animation with the following:
{_ in
  self.addRandomItem()
}
This code will add a random item to the list once the first leg of the button animation has completed. Run and enjoy the finished app:
image011
And that’s a wrap! You now know the basics of Easy Animation – a tiny animations library, which saves you lots of code lines and development time.

Where To Go From Here?

Now that you know the basics, you’re ready to try some of Easy Animation’s more advanced features.
Ever wanted to stop a repeating view animation? Easy Animation lets you do even that!
If you want to learn more, check out our book iOS Animations by Tutorials. In the book, which is fully updated for Swift 2.0 and iOS 9, you’ll learn how to animate with springs, transitions, keyframe animations, CALayer animations, Auto Layout constraint animations, view controller transition animations, and more.
We hope you enjoyed this tutorial, and if you have any questions or comments, please join the forum discussion below!
Share on Google Plus

About Divya

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment