Animating Views with Blocks example

Apple introduced blocks recently. In the UIView animation documentation, the old way of doing animation is discouraged:

Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.

So what is block-based animation methods? Here is an example:

CGPoint originalCenter = icon.center;
[UIView animateWithDuration:2.0
		animations:^{ 
			CGPoint center = icon.center;
			center.y += 60;
			icon.center = center;
		} 
		completion:^(BOOL finished){

			[UIView animateWithDuration:2.0
					animations:^{ 
						icon.center = originalCenter;
					} 
					completion:^(BOOL finished){
						;
					}];
			
		}];

The above code will animate a UIImageView* icon in a 2-second animation. Once completed, another animation will move the icon back to it’s original position.

A sample project can be downloaded here.

3 Comments

  • Dan Prince
    2010/08/31 - 7:53 am | Permalink

    What is the value of icon.center when the completion block is called? I ask because there is an example in the documentation that implies you don’t have to increment the value within the animations block.

    Are you incrementing or is just going to move 60 px?

  • 2010/11/10 - 3:07 pm | Permalink

    The example move the icon from the original postion by 60 points.

  • haptic
    2011/05/28 - 6:01 am | Permalink

    Hello, Horace,

    Thank you very much indeed! Have a nice day in HK.

    Berlin, Germany

  • Leave a Reply

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

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>