在 iOS 7 之前,畫面與畫面之間的切換基本只有四條路可走:
iOS 5 帶來了 transitionFromViewController:toViewController:duration:options:animations:completion:,算是官方第一次開放容器轉場;但真正讓自定義轉場變得優雅的,是 iOS 7 引進的一整套 Transitioning API。本文就從這套 API 的分工談起,一路寫到自製容器的非交互式切換。
蘋果在這套架構裡把職責拆得很乾淨,幾乎每一個角色都對應一個協議:
UIViewControllerAnimatedTransitioning,負責「切換過程中到底發生了什麼」。UIViewControllerInteractiveTransitioning,把動畫進度交給手勢來驅動。UIViewControllerContextTransitioning,裝的是轉場所需的元資料——參與者有哪些、各自的 frame 從哪裡到哪裡。這個物件由系統建立並交給動畫控制器。UIViewControllerTransitionCoordinator,讓你能在轉場動畫進行的同時,併行跑其他動畫。換句話說,新的 API 提供兩種玩法:一是非交互式,定義好一段動畫,切換時自動播完;二是交互式,同樣定義動畫,但進度由手勢決定,使用者可以中途改變主意。iOS 7 附贈的 UIPercentDrivenInteractiveTransition 就是一個以百分比驅動的現成實作,官方在 WWDC 上也建議:要寫交互式轉場,最直接的方式就是繼承它。
由於蘋果給的都是協議,我們完全可以把每一種效果獨立成一個類,彼此不互相污染,這正是這套設計最討人喜歡的地方。
實現 UIViewControllerAnimatedTransitioning 只需要兩個必要方法:回報動畫時長,以及把動畫演出來。
@interface MTHCustomAnimator : NSObject <UIViewControllerAnimatedTransitioning>
@end
@implementation MTHCustomAnimator
// 系統給出轉場上下文,我們回報這段轉場要花多久
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)ctx {
return 1.0;
}
// 所有視圖設定與動畫都寫在這裡
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)ctx {
UIViewController *toVC = [ctx viewControllerForKey:UITransitionContextToViewControllerKey];
UIViewController *fromVC = [ctx viewControllerForKey:UITransitionContextFromViewControllerKey];
// iOS 8 以後可以直接取 view,舊系統則退回使用 controller.view
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIView *toView = [ctx viewForKey:UITransitionContextToViewKey];
[[ctx containerView] addSubview:toView];
} else {
[[ctx containerView] addSubview:toVC.view];
}
toVC.view.alpha = 0.0;
[UIView animateWithDuration:[self transitionDuration:ctx] animations:^{
// 效果很多,這裡只示範一個向左位移
fromVC.view.transform = CGAffineTransformMakeTranslation(-320, 0);
toVC.view.alpha = 1.0;
} completion:^(BOOL finished) {
fromVC.view.transform = CGAffineTransformIdentity;
// 收尾:一定要呼叫 completeTransition:
[ctx completeTransition:![ctx transitionWasCancelled]];
}];
}
@end
兩個必要方法都收到同一個參數:一個遵循 UIViewControllerContextTransitioning 的上下文物件。使用系統內建的類時,這個物件由系統的轉場代理替我們建立並傳入,我們不必操心。
有了動畫類,接下來只是「掛上去」的問題。以一個同時示範 Push 與 Present 的主控制器為例:
@interface MTHMainViewController ()
<UINavigationControllerDelegate, UIViewControllerTransitioningDelegate>
@property (nonatomic, strong) MTHCustomAnimator *customAnimator;
@property (nonatomic, strong) PDTransitionAnimator *minToMaxAnimator;
@property (nonatomic, strong) MTHNextViewController *nextVC;
// 交互控制器:遵循 UIViewControllerInteractiveTransitioning
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactionController;
@end
@implementation MTHMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
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];
// Modal 的轉場代理
_nextVC.transitioningDelegate = self;
_nextVC.modalPresentationStyle = 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];
// Modal 按鈕
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 *pan =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didClickPanGestureRecognizer:)];
[self.navigationController.view addGestureRecognizer:pan];
}
- (void)push { [self.navigationController pushViewController:_nextVC animated:YES]; }
- (void)modal { [self presentViewController:_nextVC animated:YES completion:nil]; }
#pragma mark - UINavigationControllerDelegate(iOS 7 新增)
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)nav
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC {
if (operation == UINavigationControllerOperationPush) {
return self.customAnimator;
}
return nil; // Pop 時沿用系統預設
}
- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)nav
interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animator {
// 非交互式時回傳 nil
return _interactionController;
}
#pragma mark - UIViewControllerTransitioningDelegate(Modal)
- (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;
}
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator {
return _interactionController;
}
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator {
return nil;
}
@end
以上都屬於非交互式轉場:一切照系統流程走,使用者無法中途取消或拖動進度。
UIPercentDrivenInteractiveTransition 已經實現了 UIViewControllerInteractiveTransitioning,你只要告訴它「現在完成到百分之幾」,它就會依你設定的動畫方式算出此刻該有的畫面。三個關鍵方法:
updateInteractiveTransition: 更新百分比,通常由手勢位移換算而來;finishInteractiveTransition 宣告完成,畫面補完到切換後的狀態;cancelInteractiveTransition 宣告取消,畫面退回切換前的狀態。- (void)didClickPanGestureRecognizer:(UIPanGestureRecognizer *)recognizer {
UIView *view = self.view;
if (recognizer.state == UIGestureRecognizerStateBegan) {
CGPoint location = [recognizer locationInView:view];
// 從右半邊起手才啟動轉場,避免與其他手勢打架
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];
}
self.interactionController = nil; // 結束後務必清空
}
}
直接拿原始 view 做縮放動畫代價不低,實務上更常見的做法是先截一張快照來演出。下面的 PDTransitionAnimator 示範了類似某些傳輸類 App 的收合效果,Present 與 Dismiss 共用一個類,靠 animationType 分流。
@implementation PDTransitionAnimator
#define Switch_Time 1.2
#define Button_Width 50.f
#define Button_Space 10.f
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)ctx {
return Switch_Time;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)ctx {
UIViewController *toVC = [ctx viewControllerForKey:UITransitionContextToViewControllerKey];
UIViewController *fromVC = [ctx viewControllerForKey:UITransitionContextFromViewControllerKey];
UIView *toView = toVC.view;
UIView *fromView = fromVC.view;
if (self.animationType == AnimationTypeDismiss) {
// 把畫面壓縮成右下角的一顆小方塊
UIView *snap = [toView snapshotViewAfterScreenUpdates:YES];
[ctx.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:ctx] animations:^{
[snap setFrame:[UIScreen mainScreen].bounds];
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.5 animations:^{
[ctx.containerView addSubview:toView];
snap.alpha = 0;
} completion:^(BOOL f) {
[snap removeFromSuperview];
[ctx completeTransition:![ctx transitionWasCancelled]];
}];
}];
} else {
// 反向:從右下角的小方塊展開成整個畫面
UIView *snap2 = [toView snapshotViewAfterScreenUpdates:YES];
[ctx.containerView addSubview:snap2];
UIView *snap = [fromView snapshotViewAfterScreenUpdates:YES];
[ctx.containerView addSubview:snap];
[UIView animateWithDuration:[self transitionDuration:ctx] 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) {
[snap removeFromSuperview];
[snap2 removeFromSuperview];
[ctx.containerView addSubview:toView];
[ctx completeTransition:![ctx transitionWasCancelled]];
}];
}
}
@end
關於 snapshotViewAfterScreenUpdates::iOS 7 以前要取得一個 view 的快照,得先建立 UIGraphics 影像上下文、把 layer 渲染進去、取出圖片、關閉上下文,最後塞進 UIImageView;現在一行就足夠。參數的意義是「要不要等所有效果套用之後再截圖」——傳 NO 立刻截取目前狀態,傳 YES 則會在效果套用後才截。因此下面這段只會得到一張空白快照:
[view snapshotViewAfterScreenUpdates:YES]; [view setAlpha:0.0];
系統的 UINavigationController 與 UITabBarController 都有一個 NSArray 型的 viewControllers 屬性,存放待切換的子控制器。我們也可以做一個直接繼承 UIViewController 的 ContainerViewController,自己管理一份子控制器清單。早期常見的土方法是放一個 UIScrollView,把每個子 view 的 x 依 320 遞增排開——缺點是一載入就全部實體化,而且切走之後不會釋放。
這裡用 storyboard 建立五個子控制器並集中管理:
@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; // 目前顯示的
@property (strong, nonatomic) NSArray *viewControllers; // 子控制器清單
@property (assign, nonatomic) NSInteger currentControllerIndex;
@end
@implementation FTContainerViewController
- (void)viewDidLoad {
[super viewDidLoad];
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"];
self.viewControllers = @[_photoSenderViewController, _videoSenderViewController,
_fileSenderViewController, _contactSenderViewController,
_clipboardSenderViewController];
self.selectedViewController = self.selectedViewController ?: self.viewControllers[0];
self.currentControllerIndex = 0;
}
@end
動畫控制器換一個效果,示範 spring 動畫的用法。damping 越接近 0,彈性越明顯;設為 1.0 就完全沒有回彈。
@implementation FTMthTransitionAnimator
static CGFloat const kChildViewPadding = 16;
static CGFloat const kDamping = 0.5; // 阻尼
static CGFloat const kInitialSpringVelocity = 0.5; // 初速度
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)ctx {
return 1.0;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)ctx {
UIViewController *fromVC = [ctx viewControllerForKey:UITransitionContextFromViewControllerKey];
UIViewController *toVC = [ctx viewControllerForKey:UITransitionContextToViewControllerKey];
[[ctx containerView] addSubview:toVC.view];
toVC.view.alpha = 0;
// 依起訖 frame 判斷方向
BOOL goingRight = ([ctx initialFrameForViewController:toVC].origin.x <
[ctx finalFrameForViewController:toVC].origin.x);
CGFloat transDistance = [ctx containerView].bounds.size.width + kChildViewPadding;
CGAffineTransform transform = CGAffineTransformMakeTranslation(goingRight ? transDistance : -transDistance, 0);
toVC.view.transform = CGAffineTransformInvert(transform);
[UIView animateWithDuration:[self transitionDuration:ctx] delay:0
usingSpringWithDamping:kDamping initialSpringVelocity:kInitialSpringVelocity
options:0x00 animations:^{
fromVC.view.transform = transform;
fromVC.view.alpha = 0;
toVC.view.transform = CGAffineTransformIdentity;
toVC.view.alpha = 1;
} completion:^(BOOL finished) {
fromVC.view.transform = CGAffineTransformIdentity;
[ctx completeTransition:![ctx transitionWasCancelled]];
}];
}
@end
用系統類時,上下文由框架代為建立;自製容器就得由我們扛起這份責任,實作 UIViewControllerContextTransitioning。
@interface FTMthTransitionContext : NSObject <UIViewControllerContextTransitioning>
- (instancetype)initWithFromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC
goingRight:(BOOL)goingRight;
@property (nonatomic, copy) void (^completionBlock)(BOOL didComplete);
@property (nonatomic, assign) BOOL animated;
@property (nonatomic, assign) BOOL interactive;
@end
@implementation FTMthTransitionContext
- (instancetype)initWithFromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC
goingRight:(BOOL)goingRight {
if ((self = [super init])) {
_presentationStyle = UIModalPresentationCustom;
_containerView = fromVC.view.superview;
_privateViewControllers = @{
UITransitionContextFromViewControllerKey : fromVC,
UITransitionContextToViewControllerKey : toVC,
};
// 畫面由左右兩側進出,方向與圖示按鈕的位置對應
CGFloat travelDistance = (goingRight ? -_containerView.bounds.size.width
: _containerView.bounds.size.width);
_privateDisappearingFromRect = _privateAppearingToRect = _containerView.bounds;
_privateDisappearingToRect = CGRectOffset(_containerView.bounds, travelDistance, 0);
_privateAppearingFromRect = CGRectOffset(_containerView.bounds, -travelDistance, 0);
}
return self;
}
- (CGRect)initialFrameForViewController:(UIViewController *)vc {
if (vc == [self viewControllerForKey:UITransitionContextFromViewControllerKey]) {
return self.privateDisappearingFromRect;
}
return self.privateAppearingFromRect;
}
- (CGRect)finalFrameForViewController:(UIViewController *)vc {
if (vc == [self viewControllerForKey:UITransitionContextFromViewControllerKey]) {
return self.privateDisappearingToRect;
}
return self.privateAppearingToRect;
}
- (UIViewController *)viewControllerForKey:(NSString *)key { return self.privateViewControllers[key]; }
- (void)completeTransition:(BOOL)didComplete {
if (self.completionBlock) { self.completionBlock(didComplete); }
}
// 非交互式:不允許中途取消
- (BOOL)transitionWasCancelled { return NO; }
// 非交互式:以下三個方法只有在自製交互控制器時才有意義
- (void)updateInteractiveTransition:(CGFloat)percentComplete {}
- (void)finishInteractiveTransition {}
- (void)cancelInteractiveTransition {}
@end
UISwipeGestureRecognizer *leftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swapViewControllers:)];
[leftGesture setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.view addGestureRecognizer:leftGesture];
UISwipeGestureRecognizer *rightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swapViewControllers:)];
[rightGesture setDirection:UISwipeGestureRecognizerDirectionRight];
[self.view addGestureRecognizer:rightGesture];
- (void)swapViewControllers:(UISwipeGestureRecognizer *)gesture {
if (gesture.direction == UISwipeGestureRecognizerDirectionLeft) {
if (_currentControllerIndex < 4) { _currentControllerIndex++; }
} else if (gesture.direction == UISwipeGestureRecognizerDirectionRight) {
if (_currentControllerIndex > 0) { _currentControllerIndex--; }
}
self.selectedViewController = self.viewControllers[_currentControllerIndex];
}
// 重寫 setter,把切換動作收斂到一處
- (void)setSelectedViewController:(UIViewController *)vc {
NSParameterAssert(vc);
[self _transitionToChildViewController:vc];
_selectedViewController = vc;
}
- (void)_transitionToChildViewController:(UIViewController *)toVC {
UIViewController *fromVC = self.childViewControllers.count > 0 ? self.childViewControllers[0] : nil;
if (toVC == fromVC) { return; }
UIView *toView = toVC.view;
[toView setTranslatesAutoresizingMaskIntoConstraints:YES];
toView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
toView.frame = self.view.bounds;
// addChildViewController 才是重點:動畫與上下文只是為了轉場的視覺效果
[fromVC willMoveToParentViewController:nil];
[self addChildViewController:toVC];
if (!fromVC) {
[self.view addSubview:toVC.view];
[toVC didMoveToParentViewController:self];
return;
}
FTMthTransitionAnimator *animator = [[FTMthTransitionAnimator alloc] init];
NSUInteger fromIndex = [self.viewControllers indexOfObject:fromVC];
NSUInteger toIndex = [self.viewControllers indexOfObject:toVC];
FTMthTransitionContext *ctx = [[FTMthTransitionContext alloc]
initWithFromViewController:fromVC toViewController:toVC goingRight:(toIndex > fromIndex)];
ctx.animated = YES;
ctx.interactive = NO;
ctx.completionBlock = ^(BOOL didComplete) {
[fromVC.view removeFromSuperview];
[fromVC removeFromParentViewController];
[toVC didMoveToParentViewController:self];
if ([animator respondsToSelector:@selector(animationEnded:)]) {
[animator animationEnded:didComplete];
}
};
[animator animateTransition:ctx]; // 自製上下文,必須手動傳入
}
上面示範的是自製容器的非交互式切換。之所以把手勢定義成 Swipe 而不是 Pan,正是因為缺少交互控制器,很難做出 UIScrollView 那種跟手的分頁效果。系統並沒有提供回傳交互控制器的容器型代理方法,因此若要補齊這一塊,思路必須和自製轉場上下文一樣:先想清楚系統是怎麼把這個環境搭起來的,再自行實作 UIViewControllerInteractiveTransitioning 的那幾個方法,讓百分比得以回報給動畫控制器。
總結一句:iOS 7 之後的轉場架構本質上是「協議 + 委派」,動畫、進度、資料各自獨立。理解這層分工之後,無論是換一個彈簧曲線、換一種進場方向,還是完全自製容器,都只是替換其中一塊拼圖而已。