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

iOS 自定義 Segue:打造屬於自己的轉場動畫

編輯:iOS 開發綜合

Storyboard 內建的 Push、Modal 轉場雖然方便,但當設計稿要求一個有個性的切換效果時,就必須自己寫。做法很單純:繼承 UIStoryboardSegue,然後覆寫 -(void)perform,把動畫邏輯寫在裡面。

宣告自定義 Segue

CoolSegue.h 幾乎沒有內容,只需要表明繼承關係。

#import <UIKit/UIKit.h>

@interface CoolSegue : UIStoryboardSegue
@end

在 perform 裡安排動畫

這裡的示範效果是:把目標畫面先在背景渲染成一張圖片,然後讓這張圖「縮小並旋轉飛出畫面外」,動畫結束後才真正切換控制器。這種做法比直接平移整個 view 更有記憶點,而且因為是先把 destination 轉成圖,所以轉場過程中不會出現空白畫面。

#import "CoolSegue.h"

@implementation CoolSegue

- (void)perform {
    UIViewController *source = self.sourceViewController;
    UIViewController *destination = self.destinationViewController;

    // 1. 把目標畫面渲染成圖片
    UIGraphicsBeginImageContext(destination.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [destination.view.layer renderInContext:contextRef];
    UIImage *desImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // 2. 用圖片建立一個鋪在來源畫面上的 imageView
    UIImageView *iView = [[UIImageView alloc] initWithImage:desImage];
    [iView setBackgroundColor:[UIColor grayColor]];
    iView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    iView.contentMode = UIViewContentModeCenter;
    [source.parentViewController.view addSubview:iView];

    // 3. 起始狀態:縮到 0.1 倍、旋轉 180 度、並移到右上角外
    CGAffineTransform scaleT = CGAffineTransformMakeScale(0.1, 0.1);
    CGAffineTransform rotateT = CGAffineTransformMakeRotation(M_PI);
    iView.transform = CGAffineTransformTranslate(CGAffineTransformConcat(scaleT, rotateT), 1, 1);

    CGPoint originPoint = iView.center;
    iView.center = CGPointMake(iView.bounds.size.width, iView.bounds.size.height);

    // 4. 以 Cubic 曲線回到原始狀態
    [UIView animateKeyframesWithDuration:0.8
                                   delay:0
                                 options:UIViewKeyframeAnimationOptionCalculationModeCubic
                              animations:^{
        iView.transform = CGAffineTransformIdentity;
        iView.center = originPoint;
    } completion:^(BOOL finished) {
        [self.sourceViewController presentViewController:self.destinationViewController
                                                animated:YES
                                              completion:nil];
        [iView removeFromSuperview];
    }];
}

@end

怎麼在 Storyboard 上使用

在 storyboard 檔案中拉一條 segue,然後在屬性面板把它的 style 由預設值改成 Custom,接著在 Class 欄位填入 CoolSegue,完成。之後每次觸發這條 segue,都會走你寫的 perform。

三個容易被忽略的細節:transform 的組合順序會影響最終視覺,先縮放再旋轉與反過來結果不同;animation 的 duration 別設太長,超過一秒使用者會覺得卡頓;completion 中務必移除臨時的 imageView,否則會殘留在畫面上層攔截觸控事件。

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