尝试重新创建Airbnb内部声明式转换框架的基础知识

声明式 UIKit 转换

这个项目是重新创建Airbnb内部声明式过渡框架基础知识的一个非常基本的尝试,正如Cal Stephens(@calda)在这篇Medium博客文章中描述的那样 - 这是一本非常棒的读物,我强烈建议先看看。

代码的核心是利用通用实现从一个视图控制器过渡到另一个视图控制器。UIViewControllerAnimatedTransitioning

转换由一个对象驱动,该对象是 a 到 .TransitionDefinitiontypealiasStringAnimationType

看起来像这样: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.TransitionabletransitionIdentifierString

In the project’s current state, there are 2 views that conform to – and .TransitionableCardViewTabView

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.AnimationControllerTransitionDefinitionIdentifierHierarchyIdentifierTransitionable

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 .IdentifierAnimationType

Then, there are 3 separate implementations of a protocol – , , and – which will create the animations and any necessary completion cleanup for the particular .TransitionEdgeTranslationTransitionSharedElementTransitionTranslateYTransitionAnimationType

The animations are added as key frames within a standard block and executed to completion.UIView.animate

GitHub

点击跳转