首页 > 代码库 > 使用animation效果切换两个UIView

使用animation效果切换两个UIView

 

 
- (IBAction) switchViews:(id) sender {
//开启动画
[UIView beginAnimations:@"View Flip" context:nil];
//设置动画时间 
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//判断当前显示的UIView是不是yellowViewController.
//如果显示的不是yellowViewController,它的view‘s superview就是nil.
if([[self.yellowViewController viewsuperview] == nil){
//判断yellowViewController有没有创建。
if(self.yellowViewController == nil){
//创建yellowViewController,initWithNibName根据nib文件名称创instance。
YellowViewController *_yellowViewController = [[YellowViewController alloc]
  initWithNibName:@"YellowView" bundle:nil];
self.yellowViewController = _yellowViewController;
[_yellowViewController release];
}
//设置动画转换效果为flipFromRight.
[UIView setAnimationTransition:
UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
[self.blueViewController viewWillAppear:YES];
[self.yellowViewController viewWillDisappear:YES];
[self.blueViewController.view removeFromSuperview];
[self.view insertSubview:self.yellowViewController.view atIndex:0];
[self.blueViewController viewWillDisappear:YES];
[self.yellowViewController viewWillAppear:YES];
}else{
if(self.blueViewController == nil){
BlueViewController *_blueViewController = [[BlueViewController alloc]
  initWithNibName:@"BlueView" bundle:nil];
self.blueViewController = _blueViewController;
[_blueViewController release];
}
[UIView setAnimationTransition:
UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
[self.blueViewController viewWillDisappear:YES];
[self.yellowViewController viewWillAppear:YES];
[self.yellowViewController.view removeFromSuperview];
[self.view insertSubview:self.blueViewController.view atIndex:0];
[self.blueViewController viewWillAppear:YES];
[self.yellowViewController viewWillDisappear:YES];
}
[UIView commitAnimations];
}

 

iPhone application中,view的层级关系

|---- window

       |---- subView (RootViewController ‘s View)

             |----OtherViewController ‘s View

在window出现后,调用delegate的applicationDidFinishLaunching方法,通过方法[window addSubView:rootViewController.view];来显示RootViewController的UIView给用户。所以,这个 UIView就是一个顶层的显示界面。然后通过rootViewController.view的insertSubView将yellowViewController.view显示在window中。

使用animation效果切换两个UIView