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

iOS开发中的ViewController转场切换效果实现简介

程序员文章站 2022-04-12 10:53:20
在ios7之前,view controller的切换主要有4种: push/pop,navigationviewcontroller present and...

在ios7之前,view controller的切换主要有4种:

  1. push/pop,navigationviewcontroller
  2. present and dismis modal
  3. uitabbarcontroller
  4. addchildviewcontroller(一般用于自定义的继承于 uiviewcontroller 的容器子类)

ios5,调用- (void)transitionfromviewcontroller:(uiviewcontroller *)fromviewcontroller toviewcontroller:(uiviewcontroller *)toviewcontroller duration:(nstimeinterval)duration options:(uiviewanimationoptions)options animations:(void (^)(void))animations completion:(void (^)(bool finished))completion ns_available_ios(5_0);

(1)前面3种方法这里就不多说了,很常见的系统方法.至于第四种,我在前面文章-剖析网易标签栏的效果中已经做了阐述,但是它提供的容器转场动画只可以实现一些简单的uiview动画,但是难以重用,耦合高.
(2)关键的api:
a.动画控制器 (animation controllers) 遵从 uiviewcontrolleranimatedtransitioning 协议,并且负责实际执行动画。
b.交互控制器 (interaction controllers) 通过遵从 uiviewcontrollerinteractivetransitioning 协议来控制可交互式的转场。
c.转场代理 (transitioning delegates) 根据不同的转场类型方便的提供需要的动画控制器和交互控制器。
   其中uinavigationcontrollerdelegate delegate 中新增了2个方法给navigationcontroller
               uiviewcontrollertransitioningdelegate 新增transitioningdelegate  给modal的present和dismis

复制代码 代码如下:

  uitabbarcontrollerdelegate delegate
- (id <uiviewcontrollerinteractivetransitioning>)tabbarcontroller:(uitabbarcontroller *)tabbarcontroller
interactioncontrollerforanimationcontroller: (id <uiviewcontrolleranimatedtransitioning>)animationcontroller ns_available_ios(7_0);
- (id <uiviewcontrolleranimatedtransitioning>)tabbarcontroller:(uitabbarcontroller *)tabbarcontroller
animationcontrollerfortransitionfromviewcontroller:(uiviewcontroller *)fromvc
toviewcontroller:(uiviewcontroller *)tovc ns_available_ios(7_0);

d.转场上下文 (transitioning contexts) 定义了转场时需要的元数据,比如在转场过程中所参与的视图控制器和视图的相关属性。 转场上下文对象遵从 uiviewcontrollercontexttransitioning 协议,并且这是由系统负责生成和提供的。
e.转场协调器(transition coordinators) 可以在运行转场动画时,并行的运行其他动画。 转场协调器遵从 uiviewcontrollertransitioncoordinator 协议。
(3)新的api主要提供了2种vc切换的方式:
a.非交互式切换,即定义一种从一个vc到另一个vc的动画效果,切换的时候自动播放,
b.交互式切换,这种方式同样需要定义动画效果,只是这个动画效果会根据跟随交互式手势来切换vc并同时播放动画效果。ios7提供了一个默认的基于百分比的动画实现 uipercentdriveninteractivetransition,而且根据wwdc的说明,最简单的实现交互式动画的方法就是通过继承 uipercentdriveninteractivetransition。

苹果给我们开发者提供的是都是协议接口,所以我们能够很好的单独提出来写成一个个类,在里面实现我们各种自定义效果.
(4)来看看实现uiviewcontrolleranimatedtransitioning的自定义动画类

复制代码 代码如下:
/**
 *  自定义的动画类
 *  实现协议------>@protocol uiviewcontrolleranimatedtransitioning
 *  这个接口负责切换的具体内容,也即“切换中应该发生什么”
 */ 
@interface mthcustomanimator : nsobject <uiviewcontrolleranimatedtransitioning> 
 
@end 
 
@implementation mthcustomanimator 
 
// 系统给出一个切换上下文,我们根据上下文环境返回这个切换所需要的花费时间 
- (nstimeinterval)transitionduration:(id<uiviewcontrollercontexttransitioning>)transitioncontext 

    return 1.0; 

 
// 完成容器转场动画的主要方法,我们对于切换时的uiview的设置和动画都在这个方法中完成 
- (void)animatetransition:(id<uiviewcontrollercontexttransitioning>)transitioncontext 

    // 可以看做为destination viewcontroller 
    uiviewcontroller *toviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontexttoviewcontrollerkey]; 
    // 可以看做为source viewcontroller 
    uiviewcontroller *fromviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]; 
    // 添加toview到容器上 
        // 如果是xcode6 就可以用这段 
    if ([[[uidevice currentdevice] systemversion] floatvalue] >= 8.0) 
    { 
        // ios8 sdk 新api 
        uiview *toview = [transitioncontext viewforkey:uitransitioncontexttoviewkey]; 
        //uiview *fromview = [transitioncontext viewforkey:uitransitioncontextfromviewkey]; 
        [[transitioncontext containerview] addsubview:toview]; 
    }else{ 
        // 添加toview到容器上 
        [[transitioncontext containerview] addsubview:toviewcontroller.view]; 
    } 
     
    // 如果是xcode5 就是用这段 
    [[transitioncontext containerview] addsubview:toviewcontroller.view]; 
    toviewcontroller.view.alpha = 0.0; 
    [uiview animatewithduration:[self transitionduration:transitioncontext] animations:^{ 
        // 动画效果有很多,这里就展示个左偏移 
        fromviewcontroller.view.transform = cgaffinetransformmaketranslation(-320, 0); 
        toviewcontroller.view.alpha = 1.0; 
    } completion:^(bool finished) { 
        fromviewcontroller.view.transform = cgaffinetransformidentity; 
        // 声明过渡结束-->记住,一定别忘了在过渡结束时调用 completetransition: 这个方法 
        [transitioncontext completetransition:![transitioncontext transitionwascancelled]]; 
    }]; 

       ps:从协议中两个方法可以看出,上面两个必须实现的方法需要一个转场上下文参数,这是一个遵从uiviewcontrollercontexttransitioning 协议的对象。通常情况下,当我们使用系统的类时,系统框架为我们提供的转场代理(transitioning delegates),为我们创建了转场上下文对象,并把它传递给动画控制器。
 
复制代码 代码如下:
     
// mainviewcontroller 
@interface mthmainviewcontroller () <uinavigationcontrollerdelegate,uiviewcontrollertransitioningdelegate> 
 
@property (nonatomic,strong) mthcustomanimator *customanimator; 
@property (nonatomic,strong) pdtransitionanimator *mintomaxanimator; 
@property (nonatomic,strong) mthnextviewcontroller *nextvc; 
// 交互控制器 (interaction controllers) 通过遵从 uiviewcontrollerinteractivetransitioning 协议来控制可交互式的转场。 
@property (strong, nonatomic) uipercentdriveninteractivetransition* interactioncontroller; 
@end 
 
@implementation mthmainviewcontroller 
 
- (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil 

    self = [super initwithnibname:nibnameornil bundle:nibbundleornil]; 
    if (self) { 
        // custom initialization 
    } 
    return self; 

 
- (void)viewdidload 

    [super viewdidload]; 
    // do any additional setup after loading the view. 
    self.navigationitem.title = @"demo"; 
    self.view.backgroundcolor = [uicolor yellowcolor]; 
    // 设置代理 
    self.navigationcontroller.delegate = self; 
    // 设置转场动画 
    self.customanimator = [[mthcustomanimator alloc] init]; 
    self.mintomaxanimator = [pdtransitionanimator new]; 
 
    self.nextvc = [[mthnextviewcontroller alloc] init]; 
    // present的代理和自定义设置 
    _nextvc.transitioningdelegate = self; 
    _nextvc.modalpresentationstyle = uimodalpresentationcustom; (貌似有bug)换成modaltransitionstyle = uimodalpresentationcustom 
     
    // push 
    uibutton *pushbutton = [uibutton buttonwithtype:uibuttontypesystem]; 
    pushbutton.frame = cgrectmake(140, 200, 40, 40); 
    [pushbutton settitle:@"push" forstate:uicontrolstatenormal]; 
    [pushbutton addtarget:self action:@selector(push) forcontrolevents:uicontroleventtouchupinside]; 
    [self.view addsubview:pushbutton]; 
     
    // present 
    uibutton *modalbutton = [uibutton buttonwithtype:uibuttontypesystem]; 
    modalbutton.frame = cgrectmake(265, 500, 50, 50); 
    [modalbutton settitle:@"modal" forstate:uicontrolstatenormal]; 
    [modalbutton addtarget:self action:@selector(modal) forcontrolevents:uicontroleventtouchupinside]; 
    [self.view addsubview:modalbutton]; 
     
    // 实现交互操作的手势 
    uipangesturerecognizer *panrecognizer = [[uipangesturerecognizer alloc] initwithtarget:self action:@selector(didclickpangesturerecognizer:)]; 
    [self.navigationcontroller.view addgesturerecognizer:panrecognizer]; 

 
 
- (void)push 

    [self.navigationcontroller pushviewcontroller:_nextvc animated:yes]; 

 
- (void)modal 

    [self presentviewcontroller:_nextvc animated:yes completion:nil]; 

 
#pragma mark - uinavigationcontrollerdelegate ios7新增的2个方法 
// 动画特效 
- (id<uiviewcontrolleranimatedtransitioning>) navigationcontroller:(uinavigationcontroller *)navigationcontroller animationcontrollerforoperation:(uinavigationcontrolleroperation)operation fromviewcontroller:(uiviewcontroller *)fromvc toviewcontroller:(uiviewcontroller *)tovc 

    /**
     *  typedef ns_enum(nsinteger, uinavigationcontrolleroperation) {
     *     uinavigationcontrolleroperationnone,
     *     uinavigationcontrolleroperationpush,
     *     uinavigationcontrolleroperationpop,
     *  };
     */ 
    if (operation == uinavigationcontrolleroperationpush) { 
        return self.customanimator; 
    }else{ 
        return nil; 
    } 

 
// 交互 
- (id <uiviewcontrollerinteractivetransitioning>)navigationcontroller:(uinavigationcontroller*)navigationcontroller                           interactioncontrollerforanimationcontroller:(id <uiviewcontrolleranimatedtransitioning>)animationcontroller 

    /**
     *  在非交互式动画效果中,该方法返回 nil
     *  交互式转场,自我理解意思是,用户能通过自己的动作来(常见:手势)控制,不同于系统缺省给定的push或者pop(非交互式)
     */ 
    return _interactioncontroller; 
}  
 
#pragma mark - transitioning delegate (modal) 
// 前2个用于动画 
-(id<uiviewcontrolleranimatedtransitioning>)animationcontrollerforpresentedcontroller:(uiviewcontroller *)presented presentingcontroller:(uiviewcontroller *)presenting sourcecontroller:(uiviewcontroller *)source 

    self.mintomaxanimator.animationtype = animationtypepresent; 
    return _mintomaxanimator; 

 
-(id<uiviewcontrolleranimatedtransitioning>)animationcontrollerfordismissedcontroller:(uiviewcontroller *)dismissed 

    self.mintomaxanimator.animationtype = animationtypedismiss; 
    return _mintomaxanimator; 

 
// 后2个用于交互 
- (id <uiviewcontrollerinteractivetransitioning>)interactioncontrollerforpresentation:(id <uiviewcontrolleranimatedtransitioning>)animator 

    return _interactioncontroller; 

 
- (id <uiviewcontrollerinteractivetransitioning>)interactioncontrollerfordismissal:(id <uiviewcontrolleranimatedtransitioning>)animator 

    return nil; 

以上实现的是非交互的转场,指的是完全按照系统指定的切换机制,用户无法中途取消或者控制进度切换.那怎么来实现交互转场呢:
uipercentdriveninteractivetransition实现了uiviewcontrollerinteractivetransitioning接口的类,,可以用一个百分比来控制交互式切换的过程。我们在手势识别中只需要告诉这个类的实例当前的状态百分比如何,系统便根据这个百分比和我们之前设定的迁移方式为我们计算当前应该的ui渲染,十分方便。具体的几个重要方法:
-(void)updateinteractivetransition:(cgfloat)percentcomplete 更新百分比,一般通过手势识别的长度之类的来计算一个值,然后进行更新。之后的例子里会看到详细的用法
-(void)cancelinteractivetransition 报告交互取消,返回切换前的状态
–(void)finishinteractivetransition 报告交互完成,更新到切换后的状态

复制代码 代码如下:
#pragma mark - 手势交互的主要实现--->uipercentdriveninteractivetransition 
- (void)didclickpangesturerecognizer:(uipangesturerecognizer*)recognizer 

    uiview* view = self.view; 
    if (recognizer.state == uigesturerecognizerstatebegan) { 
        // 获取手势的触摸点坐标 
        cgpoint location = [recognizer locationinview:view]; 
        // 判断,用户从右半边滑动的时候,推出下一个vc(根据实际需要是推进还是推出) 
        if (location.x > cgrectgetmidx(view.bounds) && self.navigationcontroller.viewcontrollers.count == 1){ 
            self.interactioncontroller = [[uipercentdriveninteractivetransition alloc] init]; 
            // 
            [self presentviewcontroller:_nextvc animated:yes completion:nil]; 
        } 
    } else if (recognizer.state == uigesturerecognizerstatechanged) { 
        // 获取手势在视图上偏移的坐标 
        cgpoint translation = [recognizer translationinview:view]; 
        // 根据手指拖动的距离计算一个百分比,切换的动画效果也随着这个百分比来走 
        cgfloat distance = fabs(translation.x / cgrectgetwidth(view.bounds)); 
        // 交互控制器控制动画的进度 
        [self.interactioncontroller updateinteractivetransition:distance]; 
    } else if (recognizer.state == uigesturerecognizerstateended) { 
        cgpoint translation = [recognizer translationinview:view]; 
        // 根据手指拖动的距离计算一个百分比,切换的动画效果也随着这个百分比来走 
        cgfloat distance = fabs(translation.x / cgrectgetwidth(view.bounds)); 
        // 移动超过一半就强制完成 
        if (distance > 0.5) { 
            [self.interactioncontroller finishinteractivetransition]; 
        } else { 
            [self.interactioncontroller cancelinteractivetransition]; 
        } 
        // 结束后一定要置为nil 
        self.interactioncontroller = nil; 
    } 

最后,给大家分享一个动画特效:类似于飞兔云传的发送viewcontroller切换

复制代码 代码如下:
@implementation pdtransitionanimator 
 
#define switch_time 1.2 
- (nstimeinterval)transitionduration:(id <uiviewcontrollercontexttransitioning>)transitioncontext { 
    return switch_time; 

 
#define button_width 50.f 
#define button_space 10.f 
- (void)animatetransition:(id <uiviewcontrollercontexttransitioning>)transitioncontext { 
    uiviewcontroller* toviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontexttoviewcontrollerkey]; 
    uiviewcontroller* fromviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]; 
 
    uiview * toview = toviewcontroller.view; 
    uiview * fromview = fromviewcontroller.view; 
     
    if (self.animationtype == animationtypedismiss) { 
        // 这个方法能够高效的将当前显示的view截取成一个新的view.你可以用这个截取的view用来显示.例如,也许你只想用一张截图来做动画,毕竟用原始的view做动画代价太高.因为是截取了已经存在的内容,这个方法只能反应出这个被截取的view当前的状态信息,而不能反应这个被截取的view以后要显示的信息.然而,不管怎么样,调用这个方法都会比将view做成截图来加载效率更高. 
        uiview * snap = [toview snapshotviewafterscreenupdates:yes]; 
        [transitioncontext.containerview addsubview:snap]; 
        [snap setframe:cgrectmake([uiscreen mainscreen].bounds.size.width - button_width - button_space, [uiscreen mainscreen].bounds.size.height - button_width - button_space, button_width, button_width)]; 
         
        [uiview animatewithduration:[self transitionduration:transitioncontext] animations:^{ 
            [snap setframe:[uiscreen mainscreen].bounds]; 
        } completion:^(bool finished) { 
            [uiview animatewithduration:0.5 animations:^{ 
                [[transitioncontext containerview] addsubview:toview]; 
                snap.alpha = 0;  
            } completion:^(bool finished) { 
                [snap removefromsuperview]; 
                [transitioncontext completetransition:![transitioncontext transitionwascancelled]]; 
            }]; 
        }]; 
    } else { 
        uiview * snap2 = [toview snapshotviewafterscreenupdates:yes]; 
        [transitioncontext.containerview addsubview:snap2]; 
        uiview * snap = [fromview snapshotviewafterscreenupdates:yes]; 
        [transitioncontext.containerview addsubview:snap]; 
         
        [uiview animatewithduration:[self transitionduration:transitioncontext] animations:^{ 
            [snap setframe:cgrectmake([uiscreen mainscreen].bounds.size.width - button_width - button_space+ (button_width/2), [uiscreen mainscreen].bounds.size.height - button_width - button_space + (button_width/2), 0, 0)]; 
        } completion:^(bool finished) { 
            [uiview animatewithduration:0.5 animations:^{ 
                //snap.alpha = 0; 
            } completion:^(bool finished) { 
                [snap removefromsuperview]; 
                [snap2 removefromsuperview]; 
                [[transitioncontext containerview] addsubview:toview]; 
                // 切记不要忘记了噢 
                [transitioncontext completetransition:![transitioncontext transitionwascancelled]]; 
            }]; 
        }]; 
         
    } 

其中,snapshotviewafterscreenupdates 方法的解释,我也不是很懂,反正初级来说会用就行,还可以参照下面的解析:
在ios7 以前, 获取一个uiview的快照有以下步骤: 首先创建一个uigraphics的图像上下文,然后将视图的layer渲染到该上下文中,从而取得一个图像,最后关闭图像上下文,并将图像显示在uiimageview中。现在我们只需要一行代码就可以完成上述步骤了:
复制代码 代码如下:
[view snapshotviewafterscreenupdates:no];

这个方法制作了一个uiview的副本,如果我们希望视图在执行动画之前保存现在的外观,以备之后使用(动画中视图可能会被子视图遮盖或者发生其他一些变化),该方法就特别方便。
afterupdates参数表示是否在所有效果应用在视图上了以后再获取快照。例如,如果该参数为no,则立马获取该视图现在状态的快照,反之,以下代码只能得到一个空白快照:
复制代码 代码如下:
[view snapshotviewafterscreenupdates:yes];
[view setalpha:0.0];

由于我们设置afterupdates参数为yes,而视图的透明度值被设置成了0,所以方法将在该设置应用在视图上了之后才进行快照,于是乎屏幕空空如也。另外就是……你可以对快照再进行快照……继续快照……

继续前面的内容,这一章,主要介绍自定义viewcontroller容器上视图vc的切换.先来看看系统给我们提供的容器控制器 uinavigationcontroller和uitabbarcontroller 都有一个nsarray类型的属性viewcontrollers,很明显,存储的就是需要切换的视图vc.同理,我们定义一个containerviewcontroller,是uiviewcontroller的直接子类,用来作为容器依托,额,其他属性定义详见代码吧,这里不多说了.(ps:原先我进行多个自定义视图vc切换的方法,是放置一个uiscrollview,然后把所有childviewcontroller的view的frame的x坐标,依此按320递增,大家可以自行想象下,这样不好的地方,我感觉就是所有的vc一经加载就全部实体化了,而且不会因为被切换变成暂不显示而释放掉)
偷懒下,用storyboard创建的5个childvc

复制代码 代码如下:

// containerviewcontroller 
@interface ftcontainerviewcontroller ()  
 
@property (strong, nonatomic) ftphotosenderviewcontroller       *photosenderviewcontroller; 
@property (strong, nonatomic) ftvideosenderviewcontroller       *videosenderviewcontroller; 
@property (strong, nonatomic) ftfilesenderviewcontroller        *filesenderviewcontroller; 
@property (strong, nonatomic) ftcontactsenderviewcontroller     *contactsenderviewcontroller; 
@property (strong, nonatomic) ftclipboardsenderviewcontroller   *clipboardsenderviewcontroller; 
@property (strong, nonatomic) uiviewcontroller                  *selectedviewcontroller;        // 当前选择的vc 
@property (strong, nonatomic) nsarray                           *viewcontrollers;               // childvc数组 
@property (assign, nonatomic) nsinteger                         currentcontrollerindex;         // 当前选择的vc的数组下标号 
 
 
@end 
 
@implementation ftcontainerviewcontroller 
 
#pragma mark - viewlifecycle methods 
 
- (void)viewdidload 

    [super viewdidload]; 
    // childvc 
    self.photosenderviewcontroller = [self.storyboard instantiateviewcontrollerwithidentifier:@"ftphotosenderviewcontroller"]; 
    self.videosenderviewcontroller = [self.storyboard instantiateviewcontrollerwithidentifier:@"ftvideosenderviewcontroller"]; 
    self.filesenderviewcontroller = [self.storyboard instantiateviewcontrollerwithidentifier:@"ftfilesenderviewcontroller"]; 
    self.contactsenderviewcontroller = [self.storyboard instantiateviewcontrollerwithidentifier:@"ftcontactsenderviewcontroller"]; 
    self.clipboardsenderviewcontroller = [self.storyboard instantiateviewcontrollerwithidentifier:@"ftclipboardsenderviewcontroller"]; 
    // 存储childvc的数组 
    self.viewcontrollers = @[_photosenderviewcontroller,_videosenderviewcontroller,_filesenderviewcontroller,_contactsenderviewcontroller,_clipboardsenderviewcontroller]; 
    // 缺省为下标为0的vc 
    self.selectedviewcontroller = self.selectedviewcontroller ?: self.viewcontrollers[0]; 
    self.currentcontrollerindex = 0; 


依旧,实现uiviewcontrolleranimatedtransitioning协议的animator类,不过里面换个动画效果,利用ios7新增的弹簧动画效果:
复制代码 代码如下:

#import "ftmthtransitionanimator.h" 
 
@implementation ftmthtransitionanimator 
 
static cgfloat const kchildviewpadding = 16; 
static cgfloat const kdamping = 0.5;    // damping参数代表弹性阻尼,随着阻尼值越来越接近0.0,动画的弹性效果会越来越明显,而如果设置阻尼值为1.0,则视图动画不会有弹性效果 
static cgfloat const kinitialspringvelocity = 0.5;  // 初始化弹簧速率 
 
- (nstimeinterval)transitionduration:(id<uiviewcontrollercontexttransitioning>)transitioncontext 

    return 1.0; 

 
- (void)animatetransition:(id<uiviewcontrollercontexttransitioning>)transitioncontext 

    /**
     *  - viewcontrollerforkey:我们可以通过他访问过渡的两个 viewcontroller。
     *  - containerview:两个 viewcontroller 的 containerview。
     *  - initialframeforviewcontroller 和 finalframeforviewcontroller 是过渡开始和结束时每个 viewcontroller 的 frame。
     */ 
    uiviewcontroller *fromviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]; 
    uiviewcontroller *toviewcontroller = [transitioncontext viewcontrollerforkey:uitransitioncontexttoviewcontrollerkey]; 
     
    [[transitioncontext containerview] addsubview:toviewcontroller.view]; 
    toviewcontroller.view.alpha = 0; 
    bool goingright = ([transitioncontext initialframeforviewcontroller:toviewcontroller].origin.x < [transitioncontext finalframeforviewcontroller:toviewcontroller].origin.x); 
    cgfloat transdistance = [transitioncontext containerview].bounds.size.width + kchildviewpadding; 
    cgaffinetransform transform = cgaffinetransformmaketranslation(goingright ? transdistance : -transdistance, 0); 
    // cgaffinetransforminvert 反转 
    toviewcontroller.view.transform = cgaffinetransforminvert(transform); 
//    toviewcontroller.view.transform = cgaffinetransformtranslate(toviewcontroller.view.transform, (goingright ? transdistance : -transdistance), 0); 
     
    /**
     *   ----------弹簧动画.....-------
     *  使用由弹簧的运动描述的时序曲线` animations` 。当` dampingratio`为1时,动画将平稳减速到其最终的模型值不会振荡。阻尼比小于1来完全停止前将振荡越来越多。可以使用弹簧的初始速度,以指定的速度在模拟弹簧的端部的物体被移动它附着之前。这是一个单元坐标系,其中1是指行驶总距离的动画在第二。所以,如果你改变一个物体的位置由200pt在这个动画,以及你想要的动画表现得好像物体在动,在100pt /秒的动画开始之前,你会通过0.5 。你通常会想通过0的速度。
     */ 
    [uiview animatewithduration:[self transitionduration:transitioncontext] delay:0 usingspringwithdamping:kdamping initialspringvelocity:kinitialspringvelocity options:0x00 animations:^{ 
        fromviewcontroller.view.transform = transform; 
        fromviewcontroller.view.alpha = 0; 
        // cgaffinetransformidentity  重置,初始化 
        toviewcontroller.view.transform = cgaffinetransformidentity; 
        toviewcontroller.view.alpha = 1; 
    } completion:^(bool finished) { 
        fromviewcontroller.view.transform = cgaffinetransformidentity; 
        // 声明过渡结束-->记住,一定别忘了在过渡结束时调用 completetransition: 这个方法。 
        [transitioncontext completetransition:![transitioncontext transitionwascancelled]]; 
    }]; 

 
@end 

接下来的代码,就是实现自定义容器切换的关键了.通常情况下,当我们使用系统内建的类时,系统框架为我们创建了转场上下文对象,并把它传递给动画控制器。但是在我们这种情况下,我们需要自定义转场动画,所以我们需要承担系统框架的责任,自己去创建这个转场上下文对象。

复制代码 代码如下:

@interface ftmthtransitioncontext : nsobject <uiviewcontrollercontexttransitioning> 
 
- (instancetype)initwithfromviewcontroller:(uiviewcontroller *)fromviewcontroller toviewcontroller:(uiviewcontroller *)toviewcontroller goingright:(bool)goingright; 
@property (nonatomic, copy) void (^completionblock)(bool didcomplete); 
@property (nonatomic, assign, getter=isanimated) bool animated; 
@property (nonatomic, assign, getter=isinteractive) bool interactive; // 是否交互式 
 
@property (nonatomic, strong) nsdictionary *privateviewcontrollers; 
@property (nonatomic, assign) cgrect privatedisappearingfromrect; 
@property (nonatomic, assign) cgrect privateappearingfromrect; 
@property (nonatomic, assign) cgrect privatedisappearingtorect; 
@property (nonatomic, assign) cgrect privateappearingtorect; 
@property (nonatomic, weak) uiview *containerview; 
@property (nonatomic, assign) uimodalpresentationstyle presentationstyle; 
 
@end 
 
@implementation ftmthtransitioncontext 
 
- (instancetype)initwithfromviewcontroller:(uiviewcontroller *)fromviewcontroller toviewcontroller:(uiviewcontroller *)toviewcontroller goingright:(bool)goingright { 
     
    if ((self = [super init])) { 
        self.presentationstyle = uimodalpresentationcustom; 
        self.containerview = fromviewcontroller.view.superview; 
        self.privateviewcontrollers = @{ 
                                        uitransitioncontextfromviewcontrollerkey:fromviewcontroller, 
                                        uitransitioncontexttoviewcontrollerkey:toviewcontroller, 
                                        }; 
         
        // set the view frame properties which make sense in our specialized containerviewcontroller context. views appear from and disappear to the sides, corresponding to where the icon buttons are positioned. so tapping a button to the right of the currently selected, makes the view disappear to the left and the new view appear from the right. the animator object can choose to use this to determine whether the transition should be going left to right, or right to left, for example. 
        cgfloat traveldistance = (goingright ? -self.containerview.bounds.size.width : self.containerview.bounds.size.width); 
        self.privatedisappearingfromrect = self.privateappearingtorect = self.containerview.bounds; 
        self.privatedisappearingtorect = cgrectoffset (self.containerview.bounds, traveldistance, 0); 
        self.privateappearingfromrect = cgrectoffset (self.containerview.bounds, -traveldistance, 0); 
    } 
     
    return self; 

 
- (cgrect)initialframeforviewcontroller:(uiviewcontroller *)viewcontroller { 
    if (viewcontroller == [self viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]) { 
        return self.privatedisappearingfromrect; 
    } else { 
        return self.privateappearingfromrect; 
    } 

 
- (cgrect)finalframeforviewcontroller:(uiviewcontroller *)viewcontroller { 
    if (viewcontroller == [self viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey]) { 
        return self.privatedisappearingtorect; 
    } else { 
        return self.privateappearingtorect; 
    } 

 
- (uiviewcontroller *)viewcontrollerforkey:(nsstring *)key { 
    return self.privateviewcontrollers[key]; 

 
- (void)completetransition:(bool)didcomplete { 
    if (self.completionblock) { 
        self.completionblock (didcomplete); 
    } 

 
// 非交互式,直接返回no,因为不允许交互当然也就无法操作进度取消 
- (bool)transitionwascancelled { return no; } 
 
// 非交互式,直接不进行操作,只有进行交互,下面3个协议方法才有意义,可参照系统给我们定义好的交互控制器 
// @interface uipercentdriveninteractivetransition : nsobject <uiviewcontrollerinteractivetransitioning> 
- (void)updateinteractivetransition:(cgfloat)percentcomplete {} 
- (void)finishinteractivetransition {} 
- (void)cancelinteractivetransition {} 
 
@end 

ok,准备工作都做好了,为了仿照uiscrollview的滑动切换,但又因为现在展示的是非交互式,我们定义一个swip(轻扫)手势.

复制代码 代码如下:

uiswipegesturerecognizer *leftgesture = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(swapcontroller:)]; 
[leftgesture setdirection:uiswipegesturerecognizerdirectionleft]; 
[self.view addgesturerecognizer:leftgesture]; 
 
uiswipegesturerecognizer *rightgesture = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(swapcontroller:)]; 
[rightgesture setdirection:uiswipegesturerecognizerdirectionright]; 
[self.view addgesturerecognizer:rightgesture]; 
[objc] view plaincopy
// 响应手势的方法 
- (void)swapviewcontrollers:(uiswipegesturerecognizer *)swipegesturerecognizer 

    if (swipegesturerecognizer.direction == uiswipegesturerecognizerdirectionleft) { 
        if (_currentcontrollerindex < 4) { 
            _currentcontrollerindex++; 
        } 
        nslog(@"_currentcontrollerindex = %ld",(long)_currentcontrollerindex); 
        uiviewcontroller *selectedviewcontroller = self.viewcontrollers[_currentcontrollerindex]; 
         nslog(@"%s__%d__|%@",__function__,__line__,@"右边"); 
         self.selectedviewcontroller = selectedviewcontroller; 
    } else if (swipegesturerecognizer.direction == uiswipegesturerecognizerdirectionright){ 
         nslog(@"%s__%d__|%@",__function__,__line__,@"左边"); 
        if (_currentcontrollerindex > 0) { 
            _currentcontrollerindex--; 
        } 
        uiviewcontroller *selectedviewcontroller = self.viewcontrollers[_currentcontrollerindex]; 
        self.selectedviewcontroller = selectedviewcontroller; 
    } 

 
// 重写selectedviewcontroller的setter 
- (void)setselectedviewcontroller:(uiviewcontroller *)selectedviewcontroller 

    nsparameterassert (selectedviewcontroller); 
    [self _transitiontochildviewcontroller:selectedviewcontroller]; 
    _selectedviewcontroller = selectedviewcontroller; 

 
// 切换操作(自定义的,联想我在前面文章网易标签栏切换中,系统给的transitionfromviewcontroller,是一个道理) 
- (void)_transitiontochildviewcontroller:(uiviewcontroller *)toviewcontroller 

    uiviewcontroller *fromviewcontroller = self.childviewcontrollers.count > 0 ? self.childviewcontrollers[0] : nil; 
    if (toviewcontroller == fromviewcontroller) { 
        return; 
    } 
    uiview *toview = toviewcontroller.view; 
    [toview settranslatesautoresizingmaskintoconstraints:yes]; 
    toview.autoresizingmask = uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight; 
    toview.frame = self.view.bounds; 
     
    // 自定义容器的切换,addchildviewcontroller是关键,它保证了你想要显示的vc能够加载到容器中 
    // 而所谓的动画和上下文,只是为了转场的动画效果 
    // 因此,就算用uiscrollview切换,也不能缺少addchildviewcontroller,切记!切记! 
    [fromviewcontroller willmovetoparentviewcontroller:nil]; 
    [self addchildviewcontroller:toviewcontroller]; 
     
    if (!fromviewcontroller) { 
        [self.view addsubview:toviewcontroller.view]; 
        [toviewcontroller didmovetoparentviewcontroller:self]; 
        return; 
    } 
     
    // animator 
    ftmthtransitionanimator *transitionanimator = [[ftmthtransitionanimator alloc] init]; 
    nsuinteger fromindex = [self.viewcontrollers indexofobject:fromviewcontroller]; 
    nsuinteger toindex = [self.viewcontrollers indexofobject:toviewcontroller]; 
     
    // context 
    ftmthtransitioncontext *transitioncontext = [[ftmthtransitioncontext alloc] initwithfromviewcontroller:fromviewcontroller toviewcontroller:toviewcontroller goingright:(toindex > fromindex)]; 
    transitioncontext.animated = yes; 
    transitioncontext.interactive = no; 
    transitioncontext.completionblock = ^(bool didcomplete) { 
        // 因为是非交互式,所以fromvc可以直接直接remove出its parent's children controllers array 
        [fromviewcontroller.view removefromsuperview]; 
        [fromviewcontroller removefromparentviewcontroller]; 
        [toviewcontroller didmovetoparentviewcontroller:self]; 
        if ([transitionanimator respondstoselector:@selector (animationended:)]) { 
            [transitionanimator animationended:didcomplete]; 
        } 
    }; 
    // 转场动画需要以转场上下文为依托,因为我们是自定义的context,所以要手动设置 
    [transitionanimator animatetransition:transitioncontext]; 
}

大功告成.
上面展示的就是一个基本的自定义容器的非交互式的转场切换.那交互式的呢?从上面我定义手势定义为swip而不是pan也可以看出,非交互转场,并不能完全实现uiscrollview那种分页式的效果,按照类似百分比的形式来进行fromvc和tovc的切换,因为我们缺少交互控制器.在自定义的容器中,系统是没有提供返回交互控制器的协议给我们的,查了蛮多资料,也没找到给出明确的方法,我认为,要跟实现转场上下文一样,仿照系统方法,自定义的去实现交互式的协议方法.我们就要去思考,系统是如何搭建起这个环境的.