尝试重新创建Airbnb内部声明式转换框架的基础知识
声明式 UIKit 转换
这个项目是重新创建Airbnb内部声明式过渡框架基础知识的一个非常基本的尝试,正如Cal Stephens(@calda)在这篇Medium博客文章中描述的那样 - 这是一本非常棒的读物,我强烈建议先看看。
代码的核心是利用通用实现从一个视图控制器过渡到另一个视图控制器。UIViewControllerAnimatedTransitioning
转换由一个对象驱动,该对象是 a 到 .TransitionDefinition
typealias
String
AnimationType
看起来像这样:AnimationType
enum AnimationType {
case crossfade
case edgeTranslation(_ source: EdgeTranslationSource)
case sharedElement
case translateY(_ distance: CGFloat)
}
Views that would like to be involved in a view controller transition conform to , which requires they provide a , which is just a value to identify the element in the broader context of the transition, and optionally a custom snapshot implementation. If a custom implementation is not provided, the view is simply snapshotted using the native UIKit implementation.Transitionable
transitionIdentifier
String
In the project’s current state, there are 2 views that conform to – and .Transitionable
CardView
TabView
CardView
has a custom snapshot implementation, since it is involved in a shared element transition in which it grows from its initial state to its final state. The custom implementation creates an actual copy of the view by reinstantiating it.
A simple snapshot of the view – essentially an image – would cause the card to appear stretched during the transition as its frame is animated.
TabView
does not have a custom implementation since it simply moves in and doesn’t change size.
The is provided with the and creates an for the source and destination views. This basic implementation doesn’t really create a hierarchy, but rather a flat array of objects by traversing both view hierarchies and looking for views.AnimationController
TransitionDefinition
IdentifierHierarchy
Identifier
Transitionable
The hierarchies are then diffed, resulting in an object which holds the insertions, removals, and shared identifiers between the 2 hierarchies.IdentifierDiff
For each set of identifiers, the animations are determined by switching on the object’s desired .Identifier
AnimationType
Then, there are 3 separate implementations of a protocol – , , and – which will create the animations and any necessary completion cleanup for the particular .Transition
EdgeTranslationTransition
SharedElementTransition
TranslateYTransition
AnimationType
The animations are added as key frames within a standard block and executed to completion.UIView.animate