Blocks are simple to use for creating basic animations. If you are new to blocks then you can refer the previous article about basics of blocks.

Before release of iOS 4.0 which gave birth to blocks, animation was done using UIView animation. But with release of iOS 4.0 and above, you can use blocks for basic animation instead of UIView animation if you have basic knowledge of blocks.

Here is a simple example how we were creating animation using UIView previously and how we can implement the same animation using blocks now.

Below is the code to add fade effect for UIView.

The animation code as written above, to change the alpha of UIView looks easy, but there’s an easier method in iOS 4. In iOS 4, UIView introduced some new methods which we can use that use blocks:

  • animateWithDuration:animations:
  • animateWithDuration:animations:completion:
  • animateWithDuration:delay:options:animations:completion:

Lets see how to use this methods…

Using these methods we can put all of the parameters that we would have had to write multiple lines in a single call.

Let’s replace the code written above with blocks to add fade effect in UIView by setting up its alpha from 0 to 1 with some animation duration.

Above is the simple example of using blocks for animation. Let’s go with one more example which can help you to understand benefits of using blocks in animation.

Now I want to zoom-in my view after fade-in effect. Below is the simple code which we were writing previously using [UIView beginAnimations] etc…

In traditional way we have to call the delegate method on completion of the animation and implement a method to change its frame for zoom-in effect.

If you want to simplify the code instead of calling animation delegate methods to zoom-in after fade effect, you can use blocks as given below. Block provides completion methods in which you can add code which you want to execute after completing the animation.

The above sample code uses the method which specifies a block for the animations to run, and a block of code to be called on the completion of animation.
As a result of above block, the UIView will first fade-in and then zoom-in. The main benefit of using block is we can do many things in the same domain rather than separate them to divided methods. The blocks can improve our productivity, especially for animations with several steps.

I hope this article has helped you and you can now create simple animations using blocks. Feel free to drop your queries in comment box and I will try to answer them.

 

Related resources on Blocks

Leave a Reply

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