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

2020-01-14 20:05:04刘景俊

 在animateTransition:中你需要处理以下过程:
1. 将“to”视图插入容器视图
2. 将“to”和“from”视图分别移动到自己想要的位置
3. 最后,在动画完成时千万别忘了调用completeTransition: 方法
UIViewControllerAnimatedTransitioning协议中的方法都带有一个参数:transitionContext,这是一个系统级的对象,它符合 UIView-ControllerContextTransitioning协议,我们可以从该对象中获取用于控制转场动画的必要信息,主要包括以下内容:

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

 显然,苹果公司帮助开发者完成了大部分让人讨厌的细节工作,仅仅需要我们自己完成的工作就是定义动画的初始状态和终止状态,并调整到自己满意的效果。最后我再啰嗦两句有关transitionContext的重要注意事项: 

1.获取frame的方法可能会返回CGRectZero——如果系统无法确定该frame的值具体是什么。例如,如果你使用自定义的模态视图控制器
推出动画,在结束时系统无法确定其finalFrame。
2.如果视图控制器已经从屏幕上移除了,那么获取frame的方法也会返回CGRectZero。例如在导航控制器的转场动画结束后,试图获取“from”视图的finalFrame。
你不用手动去移除“from”视图,transitionContext将自动帮你完成。
3.如果你在应用的其他地方需要使用transitionContext,你可以放心地使用动画控制器保留一个transitionContext的引用。
将动画控制器应用到转场动画中。 

现在,我们已经开发好了动画控制器,那么最后需要做的就是,将它们应用到转场动画中:我们需要对管理转场动画的UIViewController做一些操作。 

一般来说,我们只需要让UIViewController符合UIViewController-TransitioningDelegate 协议, 编写animationController-ForPresentedController和animationControllerForDismissedController方法。在我的示例应用程序中,我设置了一个属性,用来让动画控制器知道目前正在推入还是推出视图:


 -(id) 
animationControllerForPresentedController:(UIViewController 
*)presented presentingController:(UIViewController 
*)presenting sourceController:(UIViewController *)source { 
modalAnimationController.type = AnimationTypePresent; 
return modalAnimationController; 
} 
-(id) 
animationControllerForDismissedController:(UIViewController 
*)dismissed { 
modalAnimationController.type = AnimationTypeDismiss; 
return modalAnimationController; 
}