iOS开发小技巧iOS开发iOS 开发小技巧

iOS 自定义转场动画的那些事

2016-10-25  本文已影响503人  iceMaple

iOS 7 以协议的方式开放了自定义转场的 API,协议的好处是不再拘泥于具体的某个类,只要是遵守该协议的对象都能参与转场,使其可以非常灵活的使用。转场协议由5种协议组成,实际中只需要使用其中的两个或三个便能实现绝大部分的转场动画。下面就简单讲解一下使用的心得体会,最后的总结你会发现很简单。
参考: Custom Transitions Using View Controllers
喵神的博客

TransitionVC.gif

1 概念

2 自定义转场动画时你可能用到的那些方法

.
UIViewControllerContextTransitioning

这个接口用来提供切换的上下文给开发者使用,包含了从哪个VC到哪个VC等各类信息,一般不需要开发者自己实现。具体来说,iOS7的自定义切换目的之一就是切换相关代码解耦,在进行VC切换时,做切换效果实现的时候必须需要 切换前后VC的一些信息,提供一些方法,以供我们使用。

-(UIView *)containerView; 
>VC切换所发生的view容器,开发者应该将切出的view移除,将切入的view加入到该view容器中。
-(UIViewController *)viewControllerForKey:(NSString *)key; 
>提供一个key,返回对应的VC。现在的SDK中key的选择只有UITransitionContextFromViewControllerKey和UITransitionContextToViewControllerKey两种,分别表示将要切出和切入的VC。
 -(CGRect)initialFrameForViewController:(UIViewController *)vc; 
>某个VC的初始位置,可以用来做动画的计算。
-(CGRect)finalFrameForViewController:(UIViewController *)vc;
> 与上面的方法对应,得到切换结束时某个VC应在的frame。
-(void)completeTransition:(BOOL)didComplete; 
>向这个context报告切换已经完成。

UIViewControllerAnimatedTransitioning

这个接口负责切换的具体内容,即“切换中应该发生什么”。开发者在做自定义切换效果时大部分代码会是用来实现这个接口。它只有两个方法需要我们实现:

-(NSTimeInterval)transitionDuration:(id < UIViewControllerContextTransitioning >)transitionContext; 
>系统给出一个切换上下文,我们根据上下文环境返回这个切换所需要的花费时间(一般就返回动画的时间就好了,系统会用这个时间来在百分比驱动的切换中进行帧的计算)。
-(void)animateTransition:(id < UIViewControllerContextTransitioning >)transitionContext; 
>在进行切换的时候将调用该方法,我们对于切换时的UIView的设置和动画都在这个方法中完成。

UIViewControllerTransitioningDelegate

这个接口的作用比较简单单一,在需要VC切换的时候系统会像实现了这个接口的对象询问是否需要使用自定义的切换效果。这个接口共有四个类似的方法:

-(id< UIViewControllerAnimatedTransitioning >)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
>在 presented 动画中会被调用
-(id< UIViewControllerAnimatedTransitioning >)animationControllerForDismissedController:(UIViewController *)dismissed;
>在 dismiss 动画中会被调用
-(id< UIViewControllerInteractiveTransitioning >)interactionControllerForPresentation:(id < UIViewControllerAnimatedTransitioning >)animator;
-(id< UIViewControllerInteractiveTransitioning >)interactionControllerForDismissal:(id < UIViewControllerAnimatedTransitioning >)animator;

UIPercentDrivenInteractiveTransition
这是一个实现了UIViewControllerInteractiveTransitioning接口的类,为我们预先实现和提供了一系列便利的方法,可以用一个百分比来控制交互式切换的过程。一般来说我们更多地会使用某些手势来完成交互式的转移,这样使用这个类(一般是其子类,下面会讲到)的话就会非常方便。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的UI渲染,十分方便。具体的几个重要方法:

-(void)updateInteractiveTransition:(CGFloat)percentComplete
> 更新百分比,一般通过手势识别的长度之类的来计算一个值,然后进行更新。之后的例子里会看到详细的用法
-(void)cancelInteractiveTransition 
>报告交互取消,返回切换前的状态
–(void)finishInteractiveTransition 
>报告交互完成,更新到切换后的状态

UINavigationControllerDelegate

自定义navigationController转场动画的时候

- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                          interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);
>视图控制器转换返回一个非交互式动画对象使用
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);
>视图控制器转换返回一个互动的动画对象使用。

3 实战

就如上面所说转场动画遵循UIViewControllerAnimatedTransitioning协议拿到需要做动画的视图,首先建一个动画类遵循这个协议。

@interface BouncePresentAnimation : NSObject <UIViewControllerAnimatedTransitioning>

遵循这个协议后实现里面的两个方法
方法1:用来控制转场动画的时间

  - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.8f;
}

方法2:这里用来控制视图切换做动画,因为有 present 和 dismiss 所以在这里区分两个动画(需要一个type,后面会提到)
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
switch (self.type)
{
case TransitionTypePresent:
[self presentAnimation:transitionContext];
break;
case TransitionTypeDissmiss:
[self dismissAnimation:transitionContext];
break;
default:
break;
}
}
实现:具体也可以看 喵神的博客 此处为借鉴,旨在理解。

//实现present动画逻辑代码
     \\- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    // 1. Get controllers from transition context
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    //fromVC.view.hidden = YES;

    UIView * screenSnapShotView = [fromVC.view snapshotViewAfterScreenUpdates:YES];

    // 2. Set init frame for toVC
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGRect finalFrame = [transitionContext finalFrameForViewController:toVC];
    toVC.view.frame = CGRectOffset(finalFrame, 0, screenBounds.size.height);

    // 3. Add toVC's view to containerView
    UIView *containerView = [transitionContext containerView];

    [containerView insertSubview:screenSnapShotView aboveSubview:fromVC.view];

    [containerView addSubview:toVC.view];

    // 4. Do animate now
    NSTimeInterval duration = [self transitionDuration:transitionContext];

    [UIView animateWithDuration:duration
                          delay:0.0
         usingSpringWithDamping:0.6
          initialSpringVelocity:0.0
                        options:UIViewAnimationOptionTransitionFlipFromBottom
                     animations:^{
                         toVC.view.frame = finalFrame;
                     } completion:^(BOOL finished) {
                         // 5. Tell context that we completed.
                         [transitionContext completeTransition:YES];
                     }];

}
//实现dismiss动画逻辑代码
- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    
    // 1. Get controllers from transition context
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    // 2. Set init frame for fromVC
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGRect initFrame = [transitionContext initialFrameForViewController:fromVC];
    CGRect finalFrame = CGRectOffset(initFrame, 0, screenBounds.size.height);
    
    // 3. Add target view to the container, and move it to back.
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVC.view];
    [containerView sendSubviewToBack:toVC.view];
    
    // 4. Do animate now
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    [UIView animateWithDuration:duration animations:^{
        fromVC.view.frame = finalFrame;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

上面我们完成了动画部分,接下来就是要告知系统,让其去使用我们的动画。就如上面提到的需要实现UIViewControllerTransitioningDelegate,在这里你会知道present和dismiss,所以在这里你可以传个type告知你需要的是那种动画,从而让你的动画类去实现相应动画。
present 时会触发的代理,这个时候告诉它我们需要的present动画

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [BouncePresentAnimation transitionWithTransitionType:TransitionTypePresent];
}

dismiss 时会触发的代理,这个时候告诉它我们需要的dismiss动画

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [BouncePresentAnimation transitionWithTransitionType:TransitionTypeDissmiss];
}

当然前提是你遵从了它的代理,你可以让前一个控制器作为后者的代理去实现这些方法。

 ModalViewController *mvc =  [[ModalViewController alloc] init];
 mvc.transitioningDelegate = self;
 mvc.delegate = self;
 [self presentViewController:mvc animated:YES completion:nil];

和present一样,如果想要自定义动画,需要遵循UIViewControllerAnimatedTransitioning协议

@interface PushAnimation : NSObject<UIViewControllerAnimatedTransitioning>

同样的实现协议里的两个方法

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 1.0f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    self.transitionContext = transitionContext;
    
    switch (self.type)
    {
        case TransitionAnimTypePop:
            [self transitionAnimTypePopWithTransitionContext:transitionContext];
            break;
        case TransitionAnimTypePush:
             [self transitionAnimTypePushWithTransitionContext:transitionContext];
            break;
        default:
            break;
    }
    
}

同样的,你需要遵守 UINavigationControllerDelegate ,并在它的代理方法里面实现你要的动画
添加代理

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.delegate = self;
}

实现动画

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC
{
    if (operation == UINavigationControllerOperationPush)
    {

        return [PushAnimation transitionWithTransitionType:
                TransitionAnimTypePush];
    }
    else if (operation == UINavigationControllerOperationPop)
    {
        return [PushAnimation transitionWithTransitionType:
                        TransitionAnimTypePop];

    }
    //返回nil则使用默认的动画效果
    return nil;
}

如上所述,手势动画需要 UIPercentDrivenInteractiveTransition实现,提供了一系列便利的方法,可以用一个百分比来控制交互式切换的过程。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的UI渲染,使动画过渡的更加自然。
首先我们新建一个手势处理类SwipeUpInteractiveTransition继承于UIPercentDrivenInteractiveTransition这样我们可以获取相应的父类方法。
首先给所在的控制器的view添加手势

[self.transitionController wireToViewController:mvc];

主要运用的手势控制

- (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer {
    CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
    switch (gestureRecognizer.state)
    {
        case UIGestureRecognizerStateBegan:
            // 1. Mark the interacting flag. Used when supplying it in delegate.
            self.interacting = YES;
            [self.presentingVC dismissViewControllerAnimated:YES completion:nil];
            break;
        case UIGestureRecognizerStateChanged:
        {
            // 2. Calculate the percentage of guesture
            CGFloat fraction = (translation.y / KWindowHeight);
            //Limit it between 0 and 1
            fraction = fminf(fmaxf(fraction, 0.0), 1.0);
            NSLog(@"fraction==%f",fraction);
            self.shouldComplete = (fraction > 0.5);
            [self updateInteractiveTransition:fraction];
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        {
            // 3. Gesture over. Check if the transition should happen or not
            self.interacting = NO;
            if (!self.shouldComplete || gestureRecognizer.state == UIGestureRecognizerStateCancelled)
            {
                [self cancelInteractiveTransition];
            }
            else
            {
                [self finishInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}

注:在push动画中的layer动画可以任意替换为其他转场动画,只用把动画加到 containerView.layer 上即可。CATransition 动画传送门

containerView.layer addAnimation:transition forKey:nil`

照例放Demo,仅供参考
Demo地址:
https://github.com/yongliangP/iOS-TransitionVC
如果你觉得对你有帮助请点喜欢哦,也可以关注我,每周至少一篇技术。
或者关注 我的专题 每周至少5篇更新,多谢支持哈。

上一篇下一篇

猜你喜欢

热点阅读