iOS 转场动画

转场动画,就是Vc切换过程中的过渡动画。
官方支持以下几种方式的自定义转场:
1、我们最常见的在 UINavigationController 中 push 和 pop;
2、也是比较常见的在 UITabBarController 中切换 Tab;
3、Modal 转场:presentation 和 dismissal;
4、UICollectionViewController 的布局转场:UICollectionViewController 与 UINavigationController 结合的转场方式;

如果需要更定制化的动画就需要自定义设计转场了。本文集中于presentation-dismissal的自定义转场动画。

首先这里介绍一下系统自带的动画效果

@property(nonatomic,assign) UIModalTransitionStyle modalTransitionStyle NS_AVAILABLE_IOS(3_0);
@property(nonatomic,assign) UIModalPresentationStyle modalPresentationStyle NS_AVAILABLE_IOS(3_2);

UIViewController有modalTransitionStyle和modalPresentationStyle这两个属性,

  • modalTransitionStyle 系统自带的几种过渡动画。
typedef NS_ENUM(NSInteger, UIModalTransitionStyle) {
        UIModalTransitionStyleCoverVertical = 0,      //自下而上覆盖
        UIModalTransitionStyleFlipHorizontal __TVOS_PROHIBITED,    //翻转
        UIModalTransitionStyleCrossDissolve,        //渐显
        UIModalTransitionStylePartialCurl NS_ENUM_AVAILABLE_IOS(3_2)   __TVOS_PROHIBITED,    //翻页效果
};
  • modalPresentationStyle 当你用present的方式呈现一个viewController的时候,可以设置将要弹出的viewcontroller的展示样式。
typedefNS_ENUM(NSInteger, UIModalPresentationStyle) {
      UIModalPresentationFullScreen =0,    //全屏覆盖
      UIModalPresentationPageSheet,//在portrait时是FullScreen,在landscape时和FormSheet模式一样。
      UIModalPresentationFormSheet,// 会将窗口缩小,使之居于屏幕中间。在portrait和landscape下都一样,但要注意landscape下如果软键盘出现,窗口位置会调整。
      UIModalPresentationCurrentContext,//这种模式下,presented VC的弹出方式和presenting VC的父VC的方式相同。
      UIModalPresentationCustom,//自定义视图展示风格,由一个自定义演示控制器和一个或多个自定义动画对象组成。符合UIViewControllerTransitioningDelegate协议。使用视图控制器的transitioningDelegate设定您的自定义转换。presentingVc的视图不会被移除
      UIModalPresentationOverFullScreen,//presentingVc的视图不会被移除,如果视图没有被填满,presentingVc的视图可以透过
      UIModalPresentationOverCurrentContext,//视图全部被透过
      UIModalPresentationPopover,
      UIModalPresentationNone ,
};

关于系统提供的转场动画可点击传送至 https://www.jianshu.com/p/2a1f3c424cfe

  • presentingViewController和presentedViewController,fromView和toView


    The from and to objects

    Presented和Presenting是一组相对的概念,它不受present或dismiss的影响,如果是从A视图控制器present到B,那么A总是B的presentingViewController,B总是A的presentedViewController。
    这张图示说明,我们还可以理解一下fromView和toView这个两个概念:
    fromView表示当前视图toView表示要跳转到的视图。如果是从A视图控制器present到B,则A是fromView,B是toView。从B视图控制器dismiss到A时,B变成了fromView,A是toView。

自定义转场动画中几个关键协议

  • 转场协议 UIViewControllerTransitioningDelegate
    UIViewController的transitioningDelegate属性为遵守UIViewControllerTransitioningDelegate协议的对象
 // Present过程中返回一个遵守 <UIViewControllerAnimatedTransitioning> 协议的对象,也就是实现动画过程的对象
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
 // dismiss过程中返回一个遵守 <UIViewControllerAnimatedTransitioning> 协议的对象,也就是实现动画过程的对象
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed;
//如果delegate实现了此方法,在转场过程中会调用,可根据是否有手势来判断是否返回交互控制对象
- (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator;
//如果delegate实现了此方法,在转场过程中会调用,可根据是否有手势来判断是否返回交互控制对象
- (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator;
/* 返回一个UIPresentationController的子类对象,UIPresentationController,提供了四个函数来定义present和dismiss动画开始前后的操作:
       1、presentationTransitionWillBegin: present将要执行时
       2、presentationTransitionDidEnd:    present执行结束后
       3、dismissalTransitionWillBegin:    dismiss将要执行时
       4、dismissalTransitionDidEnd:         dismiss执行结束后
*/
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(nullable UIViewController *)presenting sourceViewController:(UIViewController *)source NS_AVAILABLE_IOS(8_0);

  • 动画协议 UIViewControllerAnimatedTransitioning
    转场动画的执行由此协议控制
//返回动画执行的时长
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;
// 转场动画就是在这个方法里面添加
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;
  • 转场环境协议 UIViewControllerContextTransitioning
    动画协议UIViewControllerAnimatedTransitioning 的两个方法都有个遵守UIViewControllerContextTransitioning协议的参数,表示的是当前转场的上下文,可以获取到 fromViewController、或者是toViewController以及fromView、toView、contentView等。

简单示例

Demo地址 https://github.com/YanLYM/YMTransitionDemo

  • 渐显动画
//FromViewController中
- (void)event_present {
    YMFadeToViewController *vc = [YMFadeToViewController new];
    vc.transitioningDelegate = self;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}
//实现代理方法
#pragma mark - UIViewControllerTransitioningDelegate
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return [YMFadeInAnimate new];
}
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [YMFadeInAnimate new];
}
//此转场不涉及手势交互,所以不需要实现其它协议方法
//YMFadeInAnimate遵守了UIViewControllerAnimatedTransitioning协议
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext {
    return 0.5;
}
// This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    //获取当前上下文的容器
    UIView *contentView = [transitionContext containerView];
    //fromViewController
    UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    //toViewController
    UIViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
     
    fromView.frame = [transitionContext initialFrameForViewController:fromVc];
    toView.frame = [transitionContext finalFrameForViewController:toVc];
    [contentView addSubview:toView];
    NSTimeInterval time = [self transitionDuration:transitionContext];
    fromView.alpha = 1;
    toView.alpha = 0;
    [UIView animateWithDuration:time animations:^{
        fromView.alpha = 0;
        toView.alpha = 1;
    } completion:^(BOOL finished) {
        //transitionWasCancelled 这个方法判断转场是否已经取消了,下面的completeTransition设置转场完成
        //动画结束后一定要调用completeTransition方法 来完成或取消转场
        BOOL cancelTransition = [transitionContext transitionWasCancelled];
        [transitionContext completeTransition:!cancelTransition];
    }];
}

渐显.gif
  • 交互控制器协议 UIViewControllerInteractiveTransitioning
    官方提供了一个已实现UIViewControllerInteractiveTransitioning协议的类UIPercentDrivenInteractiveTransition
    为我们预先实现和提供了一系列便利的方法,可以用一个百分比来控制交互式切换的过程,利用手势来完成这个转场。
//暂停交互 
- (void)pauseInteractiveTransition NS_AVAILABLE_IOS(10_0);
//更新方法,一般交互时候的进度更新就在这个方法里面
- (void)updateInteractiveTransition:(CGFloat)percentComplete;
//第三个是取消交互
- (void)cancelInteractiveTransition;
//第四个的话就是设置交互完成
- (void)finishInteractiveTransition;
  • 下一个栗子:手势切换Vc


    手势切换Vc.gif
- (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning>)animator {
    //有手势 返回处理交互协议对象
    if (self.gestureRecognizer) {
        //YMSwipeInteractiveTransition 继承自UIPercentDrivenInteractiveTransition
        return [[YMSwipeInteractiveTransition alloc] initWithGestureRecognizer:self.gestureRecognizer edgeForDragging:self.targetEdge];
    }
    return nil;
}

- (nullable id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning>)animator {
    if (self.gestureRecognizer) {
        return [[YMSwipeInteractiveTransition alloc] initWithGestureRecognizer:self.gestureRecognizer edgeForDragging:self.targetEdge];
    }
    return nil;
}
  //YMSwipeInteractiveTransition  中
-(void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    [super startInteractiveTransition:transitionContext];
    //保存我们的交互上下文,方便做进度更新等操作
    self.transitionContext = transitionContext;
}
//初始化时添加手势action
-(void)gestureRecognizeDidUpdate:(UIScreenEdgePanGestureRecognizer *)gestureRecognizer{
    switch (gestureRecognizer.state){
        case UIGestureRecognizerStateBegan:
            break;
        case UIGestureRecognizerStateChanged:
            // 调用updateInteractiveTransition来更新动画进度
            // 里面嵌套定义 percentForGesture 方法计算动画进度
            [self updateInteractiveTransition:[self percentForGesture:gestureRecognizer]];
            break;
        case UIGestureRecognizerStateEnded:
            //判断手势位置,要大于一般,就完成这个转场,要小于一半就取消
            if ([self percentForGesture:gestureRecognizer] >= 0.5f)
                // 完成交互转场
                [self finishInteractiveTransition];
            else
                // 取消交互转场
                [self cancelInteractiveTransition];
            break;
        default:
            [self cancelInteractiveTransition];
            break;
    }
} 
// 计算动画进度
-(CGFloat)percentForGesture:(UIScreenEdgePanGestureRecognizer *)gesture{
    UIView * transitionContainerView = self.transitionContext.containerView;
    // 手势滑动 在transitionContainerView中 的位置
    // 这个位置判断的方法可以具体根据你的需求确定
    CGPoint locationInSourceView = [gesture locationInView:transitionContainerView];
    CGFloat width  = CGRectGetWidth(transitionContainerView.bounds);
    CGFloat height = CGRectGetHeight(transitionContainerView.bounds);
    if (self.edge == UIRectEdgeRight)
        return (width - locationInSourceView.x) / width;
    else if (self.edge == UIRectEdgeLeft)
        return locationInSourceView.x / width;
    else if (self.edge == UIRectEdgeBottom)
        return (height - locationInSourceView.y) / height;
    else if (self.edge == UIRectEdgeTop)
        return locationInSourceView.y / height;
    else
        return 0.f;
}
这里值得注意的是,UIViewControllerTransitioningDelegate代理中返回 动画协议对象 的方法,有些文章说当执行交互式转场式不会调用,经测试,在调用返回交互控制协议对象之前会先调用 - (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;因为动画还是由其控制,只是进度百分比由交互控制协议对象控制。
  • 转场协调器协议 UIViewControllerTransitionCoordinator
- (BOOL)animateAlongsideTransition:(void (^ __nullable)(id <UIViewControllerTransitionCoordinatorContext>context))animation
                        completion:(void (^ __nullable)(id <UIViewControllerTransitionCoordinatorContext>context))completion;

- (BOOL)animateAlongsideTransitionInView:(nullable UIView *)view
                               animation:(void (^ __nullable)(id <UIViewControllerTransitionCoordinatorContext>context))animation
                              completion:(void (^ __nullable)(id <UIViewControllerTransitionCoordinatorContext>context))completion;

- (void)notifyWhenInteractionEndsUsingBlock: (void (^)(id <UIViewControllerTransitionCoordinatorContext>context))handler NS_DEPRECATED_IOS(7_0, 10_0,"Use notifyWhenInteractionChangesUsingBlock");

- (void)notifyWhenInteractionChangesUsingBlock: (void (^)(id <UIViewControllerTransitionCoordinatorContext>context))handler NS_AVAILABLE_IOS(10_0);

可在转场动画发生的同时并行执行其他的动画,其作用与其说协调不如说辅助,主要在 Modal 转场和交互转场取消时使用,其他时候很少用到;遵守<UIViewControllerTransitionCoordinator>协议;由 UIKit 在转场时生成,UIViewController 在 iOS 7 中新增了方法transitionCoordinator()返回一个遵守该协议的对象,且该方法只在该控制器处于转场过程中才返回一个此类对象,不参与转场时返回 nil。转场协调器的使用可结合UIPresentationController使用。

  • UIPresentationController
    UIPresentationController,它提供了四个函数来定义present和dismiss动画开始前后的操作:

     1、presentationTransitionWillBegin: present将要执行时
    
     2、presentationTransitionDidEnd:    present执行结束后
    
     3、dismissalTransitionWillBegin:    dismiss将要执行时
    
     4、dismissalTransitionDidEnd:         dismiss执行结束后
    

Example:


卡片式.gif

如果要实现图中点击空白区域实现dismiss的效果就可以通过UIPresentationController来实现了,可在presentationTransitionWillBegin: 方法中替换presentedView

/**
 present将要执行
 */
- (void)presentationTransitionWillBegin {
    self.replacePresentView = [[UIView alloc] initWithFrame:[self frameOfPresentedViewInContainerView]];
    self.replacePresentView.layer.cornerRadius = 16;
    self.replacePresentView.layer.shadowOpacity = 0.44f;
    self.replacePresentView.layer.shadowRadius = 13.f;
    self.replacePresentView.layer.shadowOffset = CGSizeMake(0, -6.f);
    UIView *presentedView = [super presentedView];
    presentedView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.replacePresentView addSubview:presentedView];
    
    UIView *dismissView = [[UIView alloc] initWithFrame:self.containerView.bounds];
    [self.containerView addSubview:dismissView];
    self.dismissView = dismissView;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gesture_dismiss)];
    [self.dismissView addGestureRecognizer:tap];
    id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;
    
    self.dismissView.alpha = 0.f;
    self.dismissView.backgroundColor = [UIColor blackColor];
    //执行转场动画的同时执行其他动画
    [transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dismissView.alpha = 0.5f;
    } completion:NULL];
    
}
- (UIView *)presentedView {
    return self.replacePresentView;
}
  • 再看一个扩散圆的例子


    扩散圆.gif

    重要的部分就是使用UIBezierPath 和 CABasicAnimation来做动画,懂得了原理,加上会做动画,转场动画实现就是如此。

- (void)presentViewControllerWithTransition:(id <UIViewControllerContextTransitioning>)transitionContext {
    UINavigationController *navVc = (UINavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    YMCircleFromViewController * fromVc = navVc.viewControllers.lastObject;
    UIViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVc.view];
    
    UIBezierPath *startCircle = [UIBezierPath bezierPathWithOvalInRect:fromVc.presentBtn.frame];
    // sqrtf 求平方根函数  pow求次方函数,这里的意思是求X的2次方,要是pow(m,9)就是求m的9次方
    CGFloat radius = sqrtf(pow(containerView.frame.size.width, 2) + pow(containerView.frame.size.height, 2));
    UIBezierPath *endCircle = [UIBezierPath bezierPathWithArcCenter:containerView.center radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = endCircle.CGPath;
    toVc.view.layer.mask = maskLayer;
    //创建路径动画
    CABasicAnimation * maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.delegate = self;
    //动画是加到layer上的,所以必须为CGPath,再将CGPath桥接为OC对象
    maskLayerAnimation.fromValue = (__bridge id)(startCircle.CGPath);
    maskLayerAnimation.toValue   = (__bridge id)((endCircle.CGPath));
    maskLayerAnimation.duration  = [self transitionDuration:transitionContext];
    
    //速度控制函数
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
    // 添加动画
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
    
}

再看一个简单的Pop/Push的开关门动画

//开门动画
- (void) {
        YMOpenViewController *vc = [YMOpenViewController new];
        self.navigationController.delegate = vc;
        [self.navigationController pushViewController:vc animated:YES];
}

//YMOpenViewController 遵守UINavigationControllerDelegate协议,并实现此代理方法
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC {
    //通过operation判断是出栈还是入栈
    if (operation == UINavigationControllerOperationPush) {
        self.animation.isPop = NO;
    } else if (operation == UINavigationControllerOperationPop) {
        self.animation.isPop = YES;
    }
    return self.animation;
}
Pop开门.gif

Demo地址再发一遍 https://github.com/YanLYM/YMTransitionDemo
至此,presentation-dismissal的自定义转场动画基本做法已讲述完毕,下篇一起学习UINavigationController 中 push 和 pop 以及 UITabBarController 中切换 Tab的转场。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容