您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 7 轉場切換(二):自訂動畫類、手勢互動與快照特效

編輯:iOS 開發綜合

上一篇介紹了 iOS 7 轉場的五大角色,可以發現蘋果給的其實是一組協議介面。這代表我們能把每一段邏輯獨立成一個類別,各自實作想要的效果。這篇就從最基礎的自訂動畫類開始。

一、實作 UIViewControllerAnimatedTransitioning

/**
 * 自訂動畫類:負責「切換時應該發生什麼事」
 */
@interface MTHCustomAnimator : NSObject <UIViewControllerAnimatedTransitioning>
@end

@implementation MTHCustomAnimator

// 動畫 duration,由上下文決定
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 1.0;
}

// 轉場動畫的主體
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *toViewController =
        [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromViewController =
        [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    [[transitionContext containerView] addSubview:toViewController.view];
    toViewController.view.alpha = 0.0;

    [UIView animateWithDuration:[self transitionDuration:transitionContext]
                     animations:^{
        // 這裡示範水平位移
        fromViewController.view.transform = CGAffineTransformMakeTranslation(-320, 0);
        toViewController.view.alpha = 1.0;
    }
                     completion:^(BOOL finished) {
        fromViewController.view.transform = CGAffineTransformIdentity;
        // 關鍵:過渡結束一定要呼叫 completeTransition:
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

@end

兩個必須實作的方法都帶有一個轉場上下文參數,它是遵循 UIViewControllerContextTransitioning 協議的物件。使用系統 API 時,轉場代理會主動建立上下文並傳給動畫控制器;自行管理容器時則需自己提供。

二、掛上代理

@interface MTHMainViewController ()
    <UINavigationControllerDelegate, UIViewControllerTransitioningDelegate>
@property (nonatomic, strong) MTHCustomAnimator *customAnimator;
@property (nonatomic, strong) PDTransitionAnimator *minToMaxAnimator;
@property (nonatomic, strong) MTHNextViewController *nextVC;
// 互動控制器:控制可互動式轉場
@property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactionController;
@end

@implementation MTHMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];

    self.customAnimator = [[MTHCustomAnimator alloc] init];
    self.minToMaxAnimator = [PDTransitionAnimator new];
    self.nextVC = [[MTHNextViewController alloc] init];

    // Push:由 navigationController 的 delegate 提供動畫
    self.navigationController.delegate = self;

    // Present:由 viewController 自己的 transitioningDelegate 提供
    _nextVC.transitioningDelegate = self;
    _nextVC.modalPresentationStyle = UIModalPresentationCustom;

    // 手勢
    UIPanGestureRecognizer *pan =
        [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(didClickPanGestureRecognizer:)];
    [self.navigationController.view addGestureRecognizer:pan];
}

#pragma mark - UINavigationControllerDelegate

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                  animationControllerForOperation:(UINavigationControllerOperation)operation
                                               fromViewController:(UIViewController *)fromVC
                                                 toViewController:(UIViewController *)toVC {
    // UINavigationControllerOperationPush / Pop
    return (operation == UINavigationControllerOperationPush) ? self.customAnimator : nil;
}

- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
          interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController {
    // 非互動式動畫回傳 nil
    return _interactionController;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (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: 更新百分比,通常由手勢位移量換算。
  • cancelInteractiveTransition 回報取消,畫面回到切換前。
  • finishInteractiveTransition 回報完成,畫面推進到切換後。
#pragma mark - 手勢互動實作

- (void)didClickPanGestureRecognizer:(UIPanGestureRecognizer *)recognizer {
    UIView *view = self.view;

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location = [recognizer locationInView:view];
        // 只有從畫面右半側往左滑,且目前僅有一層 VC 時才啟動
        if (location.x > CGRectGetMidX(view.bounds)
            && self.navigationController.viewControllers.count == 1) {
            self.interactionController = [[UIPercentDrivenInteractiveTransition alloc] init];
        }
    } 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
               || recognizer.state == UIGestureRecognizerStateCancelled) {
        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;
    }
}

四、快照特效:類飛書的轉場

下面這個動畫控制器示範了如何用快照做出「視窗縮放展開」的效果:

@implementation PDTransitionAnimator

#define Switch_Time 1.2
#define Button_Width 50.f
#define Button_Space 10.f

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return Switch_Time;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *toVC =
        [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVC =
        [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *toView = toVC.view;
    UIView *fromView = fromVC.view;

    if (self.animationType == AnimationTypeDismiss) {
        // 關閉:把目標畫面縮成一顆按鈕,再放大回全屏
        UIView *snap = [toView snapshotViewAfterScreenUpdates:YES];
        [transitionContext.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:transitionContext]
                         animations:^{
            [snap setFrame:[UIScreen mainScreen].bounds];
        }
                         completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5
                             animations:^{
                [[transitionContext containerView] addSubview:toView];
                snap.alpha = 0;
            }
                             completion:^(BOOL finished) {
                [snap removeFromSuperview];
                [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            }];
        }];
    } else {
        // 呈現:把來源畫面縮小成按鈕
        UIView *snap2 = [toView snapshotViewAfterScreenUpdates:YES];
        [transitionContext.containerView addSubview:snap2];

        UIView *snap = [fromView snapshotViewAfterScreenUpdates:YES];
        [transitionContext.containerView addSubview:snap];

        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                         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) {
            [UIView animateWithDuration:0.5
                             animations:^{ }
                             completion:^(BOOL finished) {
                [snap removeFromSuperview];
                [snap2 removeFromSuperview];
                [[transitionContext containerView] addSubview:toView];
                // 别忘了这一步
                [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            }];
        }];
    }
}

@end

關於 snapshotViewAfterScreenUpdates:

在 iOS 7 之前,要取得一個 View 的快照得自己開 UIGraphics 上下文、把 layer 渲染進去、關閉上下文、再塞進 UIImageView,好幾個步驟。現在一行就解決:

[view snapshotViewAfterScreenUpdates:NO];

這個方法會產生一個 View 的副本,特別適合「希望保存動畫前的外觀」的場景,因為動畫過程中原始 View 可能被遮蓋或改變。

參數的意義是「是否等到所有效果套用後才截圖」。若傳入 YES:

[view snapshotViewAfterScreenUpdates:YES];
[view setAlpha:0.0];

由於 alpha 會先生效,你只會得到一張空白快照。反之傳 NO 則是立刻擷取當下狀態。

用快照做動畫比直接對原始 View 操作更省資源,因為它只反映截圖當下的內容,不必維持完整的視圖階層。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved