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的转场。