iOS7新特性 ViewController转场切换(二) 系统视图控制器容器的切换动画---push pop present

http://blog.csdn.net/hmt20130412/article/details/39080445

@上一章,介绍了主要的iOS7所增加的API,可以发现,它们不是一个个死的方法,苹果给我们开发者提供的是都是协议接口,所以我们能够很好的单独提出来写成一个个类,在里面实现我们各种自定义效果.

       1.先来看看实现UIViewControllerAnimatedTransitioning的自定义动画类

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  *  自定义的动画类 
  3.  *  实现协议------>@protocol UIViewControllerAnimatedTransitioning 
  4.  *  这个接口负责切换的具体内容,也即“切换中应该发生什么” 
  5.  */  
  6. @interface MTHCustomAnimator : NSObject <UIViewControllerAnimatedTransitioning>  
  7.   
  8. @end  
  9.   
  10. @implementation MTHCustomAnimator  
  11.   
  12. // 系统给出一个切换上下文,我们根据上下文环境返回这个切换所需要的花费时间  
  13. - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext  
  14. {  
  15.     return 1.0;  
  16. }  
  17.   
  18. // 完成容器转场动画的主要方法,我们对于切换时的UIView的设置和动画都在这个方法中完成  
  19. - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext  
  20. {  
  21.     // 可以看做为destination ViewController  
  22.     UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];  
  23.     // 可以看做为source ViewController  
  24.     UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];  
  25.     // 添加toView到容器上  
  26.         // 如果是XCode6 就可以用这段  
  27.     if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)  
  28.     {  
  29.         // iOS8 SDK 新API  
  30.         UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];  
  31.         //UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];  
  32.         [[transitionContext containerView] addSubview:toView];  
  33.     }else{  
  34.         // 添加toView到容器上  
  35.         [[transitionContext containerView] addSubview:toViewController.view];  
  36.     }  
  37.       
  38.     // 如果是XCode5 就是用这段  
  39.     [[transitionContext containerView] addSubview:toViewController.view];  
  40.     toViewController.view.alpha = 0.0;  
  41.     [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{  
  42.         // 动画效果有很多,这里就展示个左偏移  
  43.         fromViewController.view.transform = CGAffineTransformMakeTranslation(-3200);  
  44.         toViewController.view.alpha = 1.0;  
  45.     } completion:^(BOOL finished) {  
  46.         fromViewController.view.transform = CGAffineTransformIdentity;  
  47.         // 声明过渡结束-->记住,一定别忘了在过渡结束时调用 completeTransition: 这个方法  
  48.         [transitionContext completeTransition:![transitionContext transitionWasCancelled]];  
  49.     }];  
  50. }  
        PS:从协议中两个方法可以看出,上面两个必须实现的方法需要一个转场上下文参数,这是一个遵从UIViewControllerContextTransitioning 协议的对象。通常情况下,当我们使用系统的类时,系统框架为我们提供的转场代理(Transitioning Delegates),为我们创建了转场上下文对象,并把它传递给动画控制器。
       
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // MainViewController  
  2. @interface MTHMainViewController () <UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>  
  3.   
  4. @property (nonatomic,strongMTHCustomAnimator *customAnimator;  
  5. @property (nonatomic,strongPDTransitionAnimator *minToMaxAnimator;  
  6. @property (nonatomic,strongMTHNextViewController *nextVC;  
  7. // 交互控制器 (Interaction Controllers) 通过遵从 UIViewControllerInteractiveTransitioning 协议来控制可交互式的转场。  
  8. @property (strongnonatomic) UIPercentDrivenInteractiveTransition* interactionController;  
  9. @end  
  10.   
  11. @implementation MTHMainViewController  
  12.   
  13. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  14. {  
  15.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  16.     if (self) {  
  17.         // Custom initialization  
  18.     }  
  19.     return self;  
  20. }  
  21.   
  22. - (void)viewDidLoad  
  23. {  
  24.     [super viewDidLoad];  
  25.     // Do any additional setup after loading the view.  
  26.     self.navigationItem.title = @"Demo";  
  27.     self.view.backgroundColor = [UIColor yellowColor];  
  28.     // 设置代理  
  29.     self.navigationController.delegate = self;  
  30.     // 设置转场动画  
  31.     self.customAnimator = [[MTHCustomAnimator alloc] init];  
  32.     self.minToMaxAnimator = [PDTransitionAnimator new];  
  33.   
  34.     self.nextVC = [[MTHNextViewController alloc] init];  
  35.     // Present的代理和自定义设置  
  36.     _nextVC.transitioningDelegate = self;  
  37.     _nextVC.modalPresentationStyle = UIModalPresentationCustom; (貌似有BUG)换成modalTransitionStyle = UIModalPresentationCustom  
  38.       
  39.     // Push  
  40.     UIButton *pushButton = [UIButton buttonWithType:UIButtonTypeSystem];  
  41.     pushButton.frame = CGRectMake(1402004040);  
  42.     [pushButton setTitle:@"Push" forState:UIControlStateNormal];  
  43.     [pushButton addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];  
  44.     [self.view addSubview:pushButton];  
  45.       
  46.     // Present  
  47.     UIButton *modalButton = [UIButton buttonWithType:UIButtonTypeSystem];  
  48.     modalButton.frame = CGRectMake(2655005050);  
  49.     [modalButton setTitle:@"Modal" forState:UIControlStateNormal];  
  50.     [modalButton addTarget:self action:@selector(modal) forControlEvents:UIControlEventTouchUpInside];  
  51.     [self.view addSubview:modalButton];  
  52.       
  53.     // 实现交互操作的手势  
  54.     UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didClickPanGestureRecognizer:)];  
  55.     [self.navigationController.view addGestureRecognizer:panRecognizer];  
  56. }  
  57.   
  58.   
  59. - (void)push  
  60. {  
  61.     [self.navigationController pushViewController:_nextVC animated:YES];  
  62. }  
  63.   
  64. - (void)modal  
  65. {  
  66.     [self presentViewController:_nextVC animated:YES completion:nil];  
  67. }  
  68.   
  69. #pragma mark - UINavigationControllerDelegate iOS7新增的2个方法  
  70. // 动画特效  
  71. - (id<UIViewControllerAnimatedTransitioning>) navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC  
  72. {  
  73.     /** 
  74.      *  typedef NS_ENUM(NSInteger, UINavigationControllerOperation) { 
  75.      *     UINavigationControllerOperationNone, 
  76.      *     UINavigationControllerOperationPush, 
  77.      *     UINavigationControllerOperationPop, 
  78.      *  }; 
  79.      */  
  80.     if (operation == UINavigationControllerOperationPush) {  
  81.         return self.customAnimator;  
  82.     }else{  
  83.         return nil;  
  84.     }  
  85. }  
  86.   
  87. // 交互  
  88. - (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController*)navigationController                           interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)animationController  
  89. {  
  90.     /** 
  91.      *  在非交互式动画效果中,该方法返回 nil 
  92.      *  交互式转场,自我理解意思是,用户能通过自己的动作来(常见:手势)控制,不同于系统缺省给定的push或者pop(非交互式) 
  93.      */  
  94.     return _interactionController;  
  95. }  
  96.   
  97. #pragma mark - Transitioning Delegate (Modal)  
  98. // 前2个用于动画  
  99. -(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source  
  100. {  
  101.     self.minToMaxAnimator.animationType = AnimationTypePresent;  
  102.     return _minToMaxAnimator;  
  103. }  
  104.   
  105. -(id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed  
  106. {  
  107.     self.minToMaxAnimator.animationType = AnimationTypeDismiss;  
  108.     return _minToMaxAnimator;  
  109. }  
  110.   
  111. // 后2个用于交互  
  112. - (id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator  
  113. {  
  114.     return _interactionController;  
  115. }  
  116.   
  117. - (id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator  
  118. {  
  119.     return nil;  
  120. }  
       @以上实现的是非交互的转场,指的是完全按照系统指定的切换机制,用户无法中途取消或者控制进度切换.那怎么来实现交互转场呢:

UIPercentDrivenInteractiveTransition实现了UIViewControllerInteractiveTransitioning接口的类,,可以用一个百分比来控制交互式切换的过程。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的UI渲染,十分方便。具体的几个重要方法:
-(void)updateInteractiveTransition:(CGFloat)percentComplete 更新百分比,一般通过手势识别的长度之类的来计算一个值,然后进行更新。之后的例子里会看到详细的用法
-(void)cancelInteractiveTransition 报告交互取消,返回切换前的状态
–(void)finishInteractiveTransition 报告交互完成,更新到切换后的状态

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #pragma mark - 手势交互的主要实现--->UIPercentDrivenInteractiveTransition  
  2. - (void)didClickPanGestureRecognizer:(UIPanGestureRecognizer*)recognizer  
  3. {  
  4.     UIView* view = self.view;  
  5.     if (recognizer.state == UIGestureRecognizerStateBegan) {  
  6.         // 获取手势的触摸点坐标  
  7.         CGPoint location = [recognizer locationInView:view];  
  8.         // 判断,用户从右半边滑动的时候,推出下一个VC(根据实际需要是推进还是推出)  
  9.         if (location.x > CGRectGetMidX(view.bounds) && self.navigationController.viewControllers.count == 1){  
  10.             self.interactionController = [[UIPercentDrivenInteractiveTransition alloc] init];  
  11.             //  
  12.             [self presentViewController:_nextVC animated:YES completion:nil];  
  13.         }  
  14.     } else if (recognizer.state == UIGestureRecognizerStateChanged) {  
  15.         // 获取手势在视图上偏移的坐标  
  16.         CGPoint translation = [recognizer translationInView:view];  
  17.         // 根据手指拖动的距离计算一个百分比,切换的动画效果也随着这个百分比来走  
  18.         CGFloat distance = fabs(translation.x / CGRectGetWidth(view.bounds));  
  19.         // 交互控制器控制动画的进度  
  20.         [self.interactionController updateInteractiveTransition:distance];  
  21.     } else if (recognizer.state == UIGestureRecognizerStateEnded) {  
  22.         CGPoint translation = [recognizer translationInView:view];  
  23.         // 根据手指拖动的距离计算一个百分比,切换的动画效果也随着这个百分比来走  
  24.         CGFloat distance = fabs(translation.x / CGRectGetWidth(view.bounds));  
  25.         // 移动超过一半就强制完成  
  26.         if (distance > 0.5) {  
  27.             [self.interactionController finishInteractiveTransition];  
  28.         } else {  
  29.             [self.interactionController cancelInteractiveTransition];  
  30.         }  
  31.         // 结束后一定要置为nil  
  32.         self.interactionController = nil;  
  33.     }  
  34. }  
       @最后,给大家分享一个动画特效:类似于飞兔云传的发送ViewController切换

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @implementation PDTransitionAnimator  
  2.   
  3. #define Switch_Time 1.2  
  4. - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext {  
  5.     return Switch_Time;  
  6. }  
  7.   
  8. #define Button_Width 50.f  
  9. #define Button_Space 10.f  
  10. - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {  
  11.     UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];  
  12.     UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];  
  13.   
  14.     UIView * toView = toViewController.view;  
  15.     UIView * fromView = fromViewController.view;  
  16.       
  17.     if (self.animationType == AnimationTypeDismiss) {  
  18.         // 这个方法能够高效的将当前显示的view截取成一个新的view.你可以用这个截取的view用来显示.例如,也许你只想用一张截图来做动画,毕竟用原始的view做动画代价太高.因为是截取了已经存在的内容,这个方法只能反应出这个被截取的view当前的状态信息,而不能反应这个被截取的view以后要显示的信息.然而,不管怎么样,调用这个方法都会比将view做成截图来加载效率更高.  
  19.         UIView * snap = [toView snapshotViewAfterScreenUpdates:YES];  
  20.         [transitionContext.containerView addSubview:snap];  
  21.         [snap setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - Button_Width - Button_Space, [UIScreen mainScreen].bounds.size.height - Button_Width - Button_Space, Button_Width, Button_Width)];  
  22.           
  23.         [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{  
  24.             [snap setFrame:[UIScreen mainScreen].bounds];  
  25.         } completion:^(BOOL finished) {  
  26.             [UIView animateWithDuration:0.5 animations:^{  
  27.                 [[transitionContext containerView] addSubview:toView];  
  28.                 snap.alpha = 0;  
  29.             } completion:^(BOOL finished) {  
  30.                 [snap removeFromSuperview];  
  31.                 [transitionContext completeTransition:![transitionContext transitionWasCancelled]];  
  32.             }];  
  33.         }];  
  34.     } else {  
  35.         UIView * snap2 = [toView snapshotViewAfterScreenUpdates:YES];  
  36.         [transitionContext.containerView addSubview:snap2];  
  37.         UIView * snap = [fromView snapshotViewAfterScreenUpdates:YES];  
  38.         [transitionContext.containerView addSubview:snap];  
  39.           
  40.         [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{  
  41.             [snap setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - Button_Width - Button_Space+ (Button_Width/2), [UIScreen mainScreen].bounds.size.height - Button_Width - Button_Space + (Button_Width/2), 00)];  
  42.         } completion:^(BOOL finished) {  
  43.             [UIView animateWithDuration:0.5 animations:^{  
  44.                 //snap.alpha = 0;  
  45.             } completion:^(BOOL finished) {  
  46.                 [snap removeFromSuperview];  
  47.                 [snap2 removeFromSuperview];  
  48.                 [[transitionContext containerView] addSubview:toView];  
  49.                 // 切记不要忘记了噢  
  50.                 [transitionContext completeTransition:![transitionContext transitionWasCancelled]];  
  51.             }];  
  52.         }];  
  53.           
  54.     }  
  55. }  
       @其中,snapshotViewAfterScreenUpdates 方法的解释,我也不是很懂,反正初级来说会用就行,还可以参照下面的解析:

在iOS7 以前, 获取一个UIView的快照有以下步骤: 首先创建一个UIGraphics的图像上下文,然后将视图的layer渲染到该上下文中,从而取得一个图像,最后关闭图像上下文,并将图像显示在UIImageView中。现在我们只需要一行代码就可以完成上述步骤了:

[view snapshotViewAfterScreenUpdates:NO]; 
这个方法制作了一个UIView的副本,如果我们希望视图在执行动画之前保存现在的外观,以备之后使用(动画中视图可能会被子视图遮盖或者发生其他一些变化),该方法就特别方便。
afterUpdates参数表示是否在所有效果应用在视图上了以后再获取快照。例如,如果该参数为NO,则立马获取该视图现在状态的快照,反之,以下代码只能得到一个空白快照:
[view snapshotViewAfterScreenUpdates:YES]; 
[view setAlpha:0.0]; 
由于我们设置afterUpdates参数为YES,而视图的透明度值被设置成了0,所以方法将在该设置应用在视图上了之后才进行快照,于是乎屏幕空空如也。另外就是……你可以对快照再进行快照……继续快照……

      最后,主要代码已经给出,我已经上传完整代码了,大家有意向的可以去下载下来看看(唉,主要是CSDN不支持gif动态图,好蛋疼,朋友在博客园的博客都支持,但是我又不喜欢博客园的风格,看来以后自己弄个域名博客是王道,后续我也会把我的一些代码分享到github上)
      @转载请注明,转自iOS@迷糊小书童

      @待续.....下一章给出自定义ViewController容器的转场.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值