0%

代码配置IBAnimatable转场动画

IBAnimatable 是由 JakeLin 在Github上开源的动画开源库,在学习 Swift 时曾经在练手项目 ShadowsocksFree 中学习使用过,其最吸引我的是可以在 StoryBoard 中直接配置转场动画,但是我在项目中一些情境下需要使用代码配置,Github上并没有找到类似的 API 介绍,最后通过阅读源码实现效果,总结如下。


10.12 更新:
文章基于 IBAnimatable 3.0/ swift 3.0

在成功导入后,StoryBoard 的转场动画就可以配置,所以源码一定是对 UIStoryboardSegue 进行了继承自定义。在 IBAnimatable 文件夹内搜索可以得到所有的结果,基于 Demo 中演示的转场动画,选择 CardSegue 设置进行查看。源码如下
swift 3.0:

1
2
3
4
open override func perform() {
destination.transitioningDelegate = TransitionPresenterManager.sharedManager().retrievePresenter(transitionAnimationType: .cards(direction: .forward))
source.present(destination, animated: true, completion: nil)
}

代码理解为为:目的 VC 的转场代理的自定义配置、源 VC 进行模态推出目的 VC 。点到 TransitionPresenterManager 注释如下:

1
TransitionPresenter Manager: Used to cache the Presenters for Present and Dismiss transitions

证明没找错。
TransitionPresenterManager 只有一个方法:

1
public func retrievePresenter(transitionAnimationType: TransitionAnimationType, transitionDuration: Duration = defaultTransitionDuration, interactiveGestureType: InteractiveGestureType? = nil) -> TransitionPresenter {)

其参数:TransitionAnimationType 点进去之后可以发现是转场动画的枚举; DurationNSTimeInterval 用于设定转场动画时间,默认是 0.75InteractiveGestureType 是对目的 VC 返回源 VC 的手势枚举,根据所选转场动画的不同手势的参数:GestureDirection 所选择的枚举值也不同。

所以当我们有代码配置 IBAnimatable 转场动画需要时只要设置目的 VCtransitioningDelegate ,用 TransitionPresenterManagerretrievePresenter 方法配置动画选项。之后用源 VC 模态化推出目的 VC 就可以。


16.10.21

需要注意的是每种转场方式的 direction 参数各自不同,不能随意设置,比如 3.0 版本 .cards(direction: ) 参数设置,只有 .backward/.forward 两种形式,设置其他参数 Xcode 不会报错,但是在运行时会有意想不到的 bug

欢迎关注我的其它发布渠道