Implement Changes Between Two Views In iPhone

This is the simple application , we will see the how to perform transitions between two views using built-in Core Animation transitions.

Step 1: Create aWindow base application using template. Give the application name “ViewChange”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: In the AppDelegate.h file we have added UIView,UIImageView, and one method (IBAction) for changing the screen. Make the following changes in the AppDelegate.h file.


@interface ViewChangeAppDelegate : NSObject {
UIWindow *window;
UIView *containerView;
UIImageView *view1;
UIImageView *view2;
BOOL transitioning;
@property (nonatomic, retain) IBOutlet UIView *containerView;



Step 4: Double click your MainWindow.xib file open it to the Interface Builder. Open the the window and drag view from the library and place it to the window. Next drag Toolbar from the library and place it buttom of the view window. Now select ViewChangeAppDelegate, and bring up connection inspector. Select from ContainerView to the view, and nextTransition to the BarButtonItem. Now save your .xib file and go back to the Xcode.

Step 5: Make the following changes in the AppDelegate.m file.


-(void)applicationDidFinishLaunching:(UIApplication *)application
UIImage *image1 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image1.png" ofType:nil]];
view1 = [[UIImageView alloc] initWithImage:image1];
UIImage *image2 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image2.png" ofType:nil]];
view2 = [[UIImageView alloc] initWithImage:image2];
view2.hidden = YES;
[containerView addSubview:view1];
[containerView addSubview:view2];
transitioning = NO;

[containerView release];
[view1 release];
[view2 release];
[super dealloc];

CATransition *transition = [CATransition animation];
transition.duration = 0.75;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

NSString *types[4] = {kCATransitionMoveIn, kCATransitionPush, kCATransitionReveal, kCATransitionFade};
NSString *subtypes[4] = {kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom};
int rnd = random() % 4;
transition.type = types[rnd];
if(rnd < 3)
transition.subtype = subtypes[random() % 4];

transitioning = YES;
transition.delegate = self;

[containerView.layer addAnimation:transition forKey:nil];

view1.hidden = YES;
view2.hidden = NO;

UIImageView *tmp = view2;
view2 = view1;
view1 = tmp;

-(void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
transitioning = NO;

[self performTransition];



Step 6: Compile and run the application on the simulator.

You can downloaded SourceCode from here ViewChange

Leave a Comment: