Search
Mobile

iPhone Developer : Assembling Views and Animations - Recipe: Swapping Views

Published 1 min readBy Programming4us Editorial Team

The UIView animation block doesn’t limit you to a single change. Recipe 1 combines size transformations with transparency changes to create a more compelling animation. It does this by adding several directives at once to the animation block. This recipe performs five actions at a time. It zooms and fades one view into place while zooming out and fading away another and then exchanges the two in the subview array list.

Notice how the viewDidLoad method prepares the back object for animation by shrinking it and making it transparent. When the swap: method first executes, that view will be ready to appear and zoom to size.

This recipe does wait for the animation to finish by providing a delegate and a simplified callback that ignores the parameters of the default callback invocation (animationDidStop:finished:context:). This code hides the bar button after it is pressed and does not return it to view until the animation completes.

Recipe 1. Combining Multiple View Changes in Animation Blocks

- (void) animationFinished: (id) sender
{
self.navigationItem.rightBarButtonItem =
BARBUTTON(@"Swap",@selector(swap:));
}

- (void) swap: (id) sender
{
self.navigationItem.rightBarButtonItem = nil;

UIView *frontObject = [[self.view subviews] objectAtIndex:2];
UIView *backObject = [[self.view subviews] objectAtIndex:1];

CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];

frontObject.alpha = 0.0f;
backObject.alpha = 1.0f;
frontObject.transform = CGAffineTransformMakeScale(0.25f, 0.25f);
backObject.transform = CGAffineTransformIdentity;
[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:2];
[UIView setAnimationDelegate:self];