iOS实现转场动画的3种方法示例

什么是转场动画

在 NavigationController 里 push 或 pop 一个 View Controller,在 TabBarController 中切换到其他 View Controller,以 Modal 方式显示另外一个 View Controller,这些都是 View Controller Transition。在 storyboard 里,每个 View Controller 是一个 Scene,View Controller Transition 便是从一个 Scene 转换到另外一个 Scene, 中文称呼其为「转场」。 顾名思义,转场动画便是 View Controller Transition 过程中的动画效果。

在 iOS 7 之前,我们只能使用系统提供的转场效果,大部分时候够用,但仅仅是够用而已,总归会有各种不如意的小地方,但我们却无力改变;iOS 7 开放了相关 API 允许我们对转场效果进行全面定制,这太棒了,自定义转场动画以及对交互手段的支持带来了无限可能。

本文主要给大家介绍了关于iOS实现转场动画的3种方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧

1.CATransition

CATransition是CAAnimation的子类,用于过渡动画或转场动画。为视图层移入移除屏幕提供转场动画。首先来看一下简单的Demo:

 CATransition *animation = [CATransition animation];
 animation.type = kCATransitionFade;
 animation.subtype = kCATransitionFromRight;
 animation.duration = 1.0;
 // 在window上执行CATransition, 即可在ViewController转场时执行动画
 [self.view.window.layer addAnimation:animation forKey:@"kTransitionAnimation"];

 AViewController *vc = [[AViewController alloc] init];
 [self presentViewController:vc animated:NO completion:nil];

将该动画添加到window.layer上,则会present或push时使用指定的转场动画。

其中最主要的两个属性就是type和subtype。

  • type:转场动画的类型。

官方SDK只提供了四种转场动画的类型,即:

CA_EXTERN NSString * const kCATransitionFade;
CA_EXTERN NSString * const kCATransitionMoveIn;
CA_EXTERN NSString * const kCATransitionPush;
CA_EXTERN NSString * const kCATransitionReveal;

私有的type:

NSString *const kCATransitionCube = @"cube";
NSString *const kCATransitionSuckEffect = @"suckEffect";
NSString *const kCATransitionOglFlip = @"oglFlip";
NSString *const kCATransitionRippleEffect = @"rippleEffect";
NSString *const kCATransitionPageCurl = @"pageCurl";
NSString *const kCATransitionPageUnCurl = @"pageUnCurl";
NSString *const kCATransitionCameraIrisHollowOpen = @"cameraIrisHollowOpen";
NSString *const kCATransitionCameraIrisHollowClose = @"cameraIrisHollowClose";
  • subtype:动画类型的方向
CA_EXTERN NSString * const kCATransitionFromRight;
CA_EXTERN NSString * const kCATransitionFromLeft;
CA_EXTERN NSString * const kCATransitionFromTop;
CA_EXTERN NSString * const kCATransitionFromBottom;

上面讲的是给window.layer添加transition,这样使得在present或push时使用指定的转场动画。

既然讲到这里了,就看一下把transition加在layer上。

看一下示例代码:

- (void)viewDidLoad {
 [super viewDidLoad];

 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 50)];

 [button setTitle:@"进入" forState:UIControlStateNormal];

 button.backgroundColor = [UIColor redColor];

 [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];

 [self.view addSubview:button];

 _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 300, 150, 150)];
 [self.view addSubview:_imageView];
 _imageView.backgroundColor = [UIColor redColor];
 _imageArray = @[[UIImage imageNamed:@"成果秀1"],[UIImage imageNamed:@"点赞他人1"],[UIImage imageNamed:@"偷师学艺1"],[UIImage imageNamed:@"学会欣赏3"]];

 _imageView.image = [UIImage imageNamed:@"成果秀1"];
}

- (void)buttonClicked{

 CATransition *animation = [CATransition animation];
 animation.type = @"cube";
 animation.subtype = kCATransitionFromRight;
 animation.duration = 1.0;
 //换图片的时候使用转场动画
 [self.imageView.layer addAnimation:animation forKey:nil];
 //cycle to next image
 UIImage *currentImage = self.imageView.image;
 NSUInteger index = [self.imageArray indexOfObject:currentImage];
 index = (index + 1) % [self.imageArray count];
 self.imageView.image = self.imageArray[index];

}

2.transitionFromViewController

UIViewController自带的方法:
transitionFromViewController:toViewController:duration:options:animations:completion:这个转场动画是用在当一个父视图控制器中有几个childViewController,当要在这几个子视图控制器之间切换时就可以用这个方法。

AViewController *a = self.childViewControllers[0];
BViewController *b = self.childViewControllers[1];
CViewController *c = self.childViewControllers[2];

// Curl 翻页效果
// UIViewAnimationOptionTransitionCurlUp, UIViewAnimationOptionTransitionCurlDown
// Flip 翻转效果
// UIViewAnimationOptionTransitionFlipFromLeft, UIViewAnimationOptionTransitionFlipFromRight
// UIViewAnimationOptionTransitionFlipFromTop, UIViewAnimationOptionTransitionFlipFromDown

[self transitionFromViewController:_currentViewController
   toViewController:b
    duration:0.5
    options:UIViewAnimationOptionTransitionFlipFromRight
   animations:^{

} completion:^(BOOL finished) {

}];

3.Transition Animation

1 UINavigationControllerDelegate + UIViewControllerAnimatedTransitioning

在UINavigationController的转场动画中,要指定UINavigationControllerDelegate对象:

self.navigationController.delegate = self;
[self.navigationController pushViewController:itemVC animated:YES];

UINavigationControllerDelegate主要有以下两个协议方法:

//pop
- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
       interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);
//push
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
         animationControllerForOperation:(UINavigationControllerOperation)operation
            fromViewController:(UIViewController *)fromVC
             toViewController:(UIViewController *)toVC NS_AVAILABLE_IOS(7_0);

首先创建一个基类PDAnimatorBaseTransition实现UIViewControllerAnimatedTransitioning协议的方法。

UIViewControllerAnimatedTransitioning协议的方法有:

//动画持续时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;
//转场动画实现细节
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;
动画结束时调用
- (void)animationEnded:(BOOL) transitionCompleted;

PDAnimatorBaseTransition.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, PDAnimationType){

 animationTypePresent = 0,
 animationTypeDismiss ,
 animationTypePush ,
 animationTypePop,
};

@interface PDAnimatorBaseTransition : NSObject <UIViewControllerAnimatedTransitioning>

@property (nonatomic, assign)PDAnimationType animationType;

@property (nonatomic, strong)UIView *containerView;

@property (nonatomic, strong)UIViewController *from;

@property (nonatomic, strong)UIViewController *to;

@property (nonatomic, strong)UIView *fromView;

@property (nonatomic, strong)UIView *toView;

@property (nonatomic, weak)id <UIViewControllerContextTransitioning> transitionContext;

@end

PDAnimatorBaseTransition.m

#import "PDAnimatorBaseTransition.h"
@interface PDAnimatorBaseTransition()
@end
@implementation PDAnimatorBaseTransition

#pragma mark -required
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{

 return 1.f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{

 _transitionContext = transitionContext;

 _containerView = [transitionContext containerView];

 _from = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

 _to = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

 if([transitionContext respondsToSelector:@selector(viewForKey:)]){

  _fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
  _toView = [transitionContext viewForKey:UITransitionContextToViewKey];
 }else{

  _fromView = _from.view;
  _toView = _to.view;
 }

 if(self.animationType == animationTypePresent){

  [self animationPresent];
 }else if (self.animationType == animationTypeDismiss){

  [self animationDismiss];
 }else if (self.animationType == animationTypePop){

  [self animationPop];
 }else{

  [self animationPush];
 }

}
#pragma mark -optional

//动画结束时回调
- (void)animationEnded:(BOOL) transitionCompleted{
}
- (void)animationPresent{
}
- (void)animationDismiss{
}
- (void)animationPop{
}
- (void)animationPush{

}

然后创建子类PDAnimatorPUshPopTransition继承自PDAnimatorBaseTransition,实现- (void)animationPush,- (void)animationPop方法。

PDAnimatorPUshPopTransition.h

#import "PDAnimatorBaseTransition.h"
#import <UIKit/UIKit.h>

@interface PDAnimatorPUshPopTransition : PDAnimatorBaseTransition
@property (nonatomic, assign)CGPoint itemCenter;

@property (nonatomic, assign)CGSize itemSize;

@property (nonatomic, strong)NSString *imageName;

@end

PDAnimatorPUshPopTransition.m

#import "PDAnimatorPUshPopTransition.h"

@implementation PDAnimatorPUshPopTransition

- (instancetype)init{

 self = [super init];
 if(self){

 }

 return self;
}

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{

 return 5.f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{

 [super animateTransition:transitionContext];
}

- (void)animationPush{

 NSTimeInterval duration = [self transitionDuration:self.transitionContext];
 __weak typeof(self) weakSelf = self;

 self.containerView.backgroundColor = [UIColor lightGrayColor];

 UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 160)];
 imageView.image = [UIImage imageNamed:self.imageName];
 imageView.center = _itemCenter;

 CGFloat initialScale = _itemSize.width / CGRectGetWidth(imageView.frame);

 CGAffineTransform transform = CGAffineTransformIdentity;

 transform = CGAffineTransformScale(transform, initialScale, initialScale);
 transform = CGAffineTransformRotate(transform, M_PI);

 imageView.layer.affineTransform = transform;

 // imageView.transform = CGAffineTransformMakeScale(initialScale, initialScale);

 [self.containerView addSubview:imageView];

 self.toView.frame = [self.transitionContext finalFrameForViewController:self.to];
 CGPoint finalCenter = self.toView.center;
 self.toView.center = finalCenter;
 self.toView.alpha = 0.0;
 //这一句一定要
 [self.containerView addSubview:self.toView];

 [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{

  imageView.layer.affineTransform = CGAffineTransformIdentity;

  imageView.center = finalCenter;

  self.fromView.alpha = 0.0;
  self.containerView.backgroundColor = [UIColor redColor];
 } completion:^(BOOL finished){

  [imageView removeFromSuperview];

  weakSelf.toView.alpha = 1.0f;
  weakSelf.fromView.alpha = 1.0f;

  [weakSelf.transitionContext completeTransition:![weakSelf.transitionContext transitionWasCancelled]];
 }];

}

- (void)animationPop{

 NSTimeInterval duration = [self transitionDuration:self.transitionContext];
 __weak typeof(self) weakSelf = self;

 self.toView.frame = [self.transitionContext finalFrameForViewController:self.to];

 [self.containerView insertSubview:self.toView belowSubview:self.fromView];

 self.fromView.alpha = 0.0;

 self.fromView.backgroundColor = [UIColor clearColor];

 [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{

  CGFloat initialScale = _itemSize.width / 200;
  weakSelf.fromView.transform = CGAffineTransformMakeScale(initialScale, initialScale);
  weakSelf.fromView.center = weakSelf.itemCenter;

  weakSelf.toView.alpha = 1.0f;
 } completion:^(BOOL finished){

  weakSelf.fromView.alpha = 0.0f;

  [weakSelf.transitionContext completeTransition:![weakSelf.transitionContext transitionWasCancelled]];
 }];
}

@end

然后我们在需要push的地方实现UINavigationControllerDelegate的协议方法:

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
           animationControllerForOperation:(UINavigationControllerOperation)operation
               fromViewController:(UIViewController *)fromVC
               toViewController:(UIViewController *)toVC NS_AVAILABLE_IOS(7_0){

 PDAnimatorPUshPopTransition *animationTransition = [[PDAnimatorPUshPopTransition alloc] init];
 if(operation == UINavigationControllerOperationPush){

  animationTransition.animationType = animationTypePush;
 }else if (operation == UINavigationControllerOperationPop){

  animationTransition.animationType = animationTypePop;
 }

 NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
 if (indexPaths.count == 0) {
  return nil;
 }

 NSIndexPath *selectedIndexPath = indexPaths[0];
 UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:selectedIndexPath];

 // 一定要加上convertPoint:toView:操作
 animationTransition.itemCenter = [self.collectionView convertPoint:cell.center toView:self.view];
 animationTransition.itemSize = cell.frame.size;
 animationTransition.imageName = [NSString stringWithFormat:@"%ld", (long)selectedIndexPath.item];

 return animationTransition;
}

2 UIViewControllerTransitioningDelegate+UIViewControllerAnimatedTransitioning

首先需要设置被present的Controller的transitionDelegate

DemoViewControllerTransitionPresentedViewController *presentedVC = [[DemoViewControllerTransitionPresentedViewController alloc] init];
presentedVC.transitionDelegate = self;
[self presentViewController:presentedVC animated:YES completion:nil];

UIViewControllerTransitioningDelegate的代理的协议方法有:

//  prenent
- (id )animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source;
//  pop
- (id )animationControllerForDismissedController:(UIViewController *)dismissed;
//  prenent
- (id )interactionControllerForPresentation:(id )animator;
//  pop
- (nullable id )interactionControllerForDismissal:(id )animator;

创建子类PDAnimationPresentTransitio继承自基类PDAnimatorBaseTransition,实现- (void)animationPresent,- (void)animationDismiss方法。

PDAnimationPresentTransition.h

#import "PDAnimatorBaseTransition.h"

@interface PDAnimationPresentTransition : PDAnimatorBaseTransition

@end

PDAnimationPresentTransition.m

#import "PDAnimationPresentTransition.h"

@implementation PDAnimationPresentTransition

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{

 return 1.f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
 [super animateTransition:transitionContext];
}

- (void)animationPresent{

 NSTimeInterval duration = [self transitionDuration:self.transitionContext];
 __weak typeof(self) weakSelf = self;

 self.toView.frame = [self.transitionContext initialFrameForViewController:self.to];

 self.fromView.frame = [self.transitionContext initialFrameForViewController:self.from];

 CGAffineTransform transform = CGAffineTransformIdentity;
 transform = CGAffineTransformScale(transform, 0.001, 0.001);
 self.toView.layer.affineTransform = transform;

 [self.containerView addSubview:self.toView];

 self.toView.alpha = 0.0;

 [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

  self.toView.layer.affineTransform = CGAffineTransformIdentity;
  self.toView.frame = [self.transitionContext finalFrameForViewController:self.to];
  self.toView.alpha = 1.0;
 } completion:^(BOOL finished){

  BOOL wasCancelled = [weakSelf.transitionContext transitionWasCancelled];
  [weakSelf.transitionContext completeTransition:!wasCancelled];
 }];

}

然后我们在需要present的地方实现UIViewControllerTransitioningDelegate的代理方法。

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{

 PDAnimationPresentTransition *animationTransition = [[PDAnimationPresentTransition alloc] init];
 animationTransition.animationType = animationTypePresent;
 return animationTransition;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{

 PDAnimationPresentTransition *animationTransition = [[PDAnimationPresentTransition alloc] init];
 animationTransition.animationType = animationTypePresent;
 return animationTransition;
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我们的支持。

(0)

相关推荐

  • 深入学习iOS7自定义导航转场动画

    在iOS7以前,开发者如果希望定制导航控制器推入推出视图时的转场动画,一般都只能通过子类化UINavigationController或者自己编写动画代码去覆盖相应的方法,现在iOS7为开发者带来了福音,苹果公司引入了大量新API,给予了开发者很高的自由度,在处理由UIViewController管理的UIView动画时,这些API使用方便,可扩展性也很强,定制起来非常轻松: 全新的针对UIView的动画block方法 全新的UIViewControllerAnimatedTransitioni

  • 详解iOS开发中的转场动画和组动画以及UIView封装动画

    一.转场动画 CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果.iOS比Mac OS X的转场动画效果少一点 UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果 属性解析: type:动画过渡类型 subtype:动画过渡方向 startProgress:动画起点(在整体动画的百分比) endProgress:动画终点(在整体动画的百分比) 转场动画代码示例 1.界面搭建 2.实现代码 复制代码

  • IOS实战之自定义转场动画详解

    转场动画这事,说简单也简单,可以通过presentViewController:animated:completion:和dismissViewControllerAnimated:completion:这一组函数以模态视图的方式展现.隐藏视图.如果用到了navigationController,还可以调用pushViewController:animated:和popViewController这一组函数将新的视图控制器压栈.弹栈. 下图中所有转场动画都是自定义的动画,这些效果如果不用自定义动

  • iOS实现类似格瓦拉电影的转场动画

    用过格瓦拉电影,或者其他app可能都知道,一种点击按钮用放大效果实现转场的动画现在很流行,效果大致如下 自定义转场动画 首先就要声明一个遵守UIViewControllerAnimatedTransitioning协议的类. 然后实现协议中的两个函数 // This is used for percent driven interactive transitions, as well as for container controllers that have companion animati

  • 实例讲解iOS中的CATransition转场动画使用

    一.简介 CATransition是CAAnimation的子类,用于做转场动画 能够为图层提供移出屏幕和移入屏幕的动画效果.iOS比Mac OS X的转场动画效果少一点 如:UINavigationController导航控制器就是通过CATransition转场动画实现了将控制器的视图推入屏幕的动画效果 CATransition头文件 动画属性: type:动画过渡类型 subtype:动画过渡方向 startProgress:动画起点(在整体动画的百分比) endProgress:动画终点

  • iOS swift实现转场动画的方法示例

    转场动画介绍 转场动画在我们日常开发中是经常遇到的,所谓转场动画,就是一个控制器的view切到另一个控制器的view上过程中过的动画效果.本例子是实现了在导航控制器的titleView边上慢慢弹出一个控制器.下面话不多说,来一起看看详细的介绍: 效果图: 专场前 专场后 示例代码 首先自定义一个animator类.在需要转场的控制器内,设置代理 //需要设置转场动画的控制器titleViewVc.transitioningDelegate = aniamator//这里的animator是ani

  • IOS登录页面动画、转场动画开发详解

    动画效果 需求分析 分析方法 下载这个gif动图,用mac默认的打开方式打开这个gif图(双击图片即可),效果如下 鼠标选中红色箭头所指的位置,然后按住键盘方向键下键,图片会以缓慢的可控的速度播放,便于分析动画的构成. 小tips:macos系统想正常浏览一个gif动图,可以鼠标单击图片后按空格,也可以选择用浏览器打开,gif图会以正常速度播放. 技术点分析 如何生成一个动画让控件执行? 现流行的方式主要有三种: 1.基本动画 2.核心动画 3.三方框架--POP框架(由Facebook开发)

  • IOS轻松几步实现自定义转场动画

    一.系统提供的转场动画 目前,系统给我们提供了push/pops和present/dismiss两种控制器之间跳转方.当然,通过设置UIModalTransitionStyle属性,可以实现下面4种modal效果,相信大家都比较熟悉了,这里就不再展示效果图. UIModalTransitionStyleCoverVertical // 从下往上, UIModalTransitionStyleFlipHorizontal // 水平翻转 UIModalTransitionStyleCrossDis

  • 详解IOS图层转场动画

    CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果.iOS比Mac OS X的转场动画效果少一点 UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果 属性解析: type:动画过渡类型 subtype:动画过渡方向 startProgress:动画起点(在整体动画的百分比) endProgress:动画终点(在整体动画的百分比) 具体代码: /* 过渡效果 fade //交叉淡化过渡(不支持过渡方

  • iOS如何自定义控制器转场动画push详解

    前言 最近有些空闲时间,整理了下最近做的项目,本文主要介绍了关于iOS自定义控制器转场动画push的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 效果图: iOS7 开始苹果推出了自定义转场的 API .从此,任何可以用 CoreAnimation 实现的动画,都可以出现在两个 ViewController 的切换之间.并且实现方式高度解耦,这也意味着在保证代码干净的同时想要替换其他动画方案时只需简单改一个类名就可以了,真正体会了一把高颜值代码带来的愉悦感. 其实网

随机推荐