欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-11-25 12:32:22
什么是转场动画 在 navigationcontroller 里 push 或 pop 一个 view controller,在 tabbarcontroller 中...

什么是转场动画

在 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;
}

总结

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