iOS 自定義轉場動畫淺談


代碼地址如下:
http://www.demodashi.com/demo/11612.html

路漫漫其修遠兮,吾將上下而求索

kaipingtu.gif

前記

想研究自定義轉場動畫很久了,時間就像海綿,擠一擠還是有的,花了差不多有10天的時間,終於對轉場動畫了解了一點。自從iOS 7以后,我們就可以自定義轉場動畫,實現我們想要的效果,在這之前,我們先來看一張圖,大概了解下,需要知道些什么

相關類聯系圖

Paste_Image.png

相信各位看官也差不多看完這張圖了,下面我們就來簡單了解下其中的類和相關的函數

說到轉場動畫,其實無非就是我們常用的push pop present dismiss四種動畫,其中前面兩個是成對使用,后面兩個成對使用,我們先看看push這組在自定義轉場動畫中所涉及到的類

由於push動畫組需要配合navigationController來使用,所以上圖中的UINavigationControllerDelegate肯定是我們需要的類

UINavigationControllerDelegate

先來看看其中需要用到的函數

- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                          interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);

第一個函數的返回值是一個id <UIViewControllerInteractiveTransitioning>
第二個函數返回的值是一個id <UIViewControllerAnimatedTransitioning>
那么我們就先從這兩個返回值入手,來看下兩個函數的作用

UIViewControllerInteractiveTransitioning 、UIPercentDrivenInteractiveTransition

這兩個類又是干什么的呢?UIPercentDrivenInteractiveTransition遵守協議UIViewControllerInteractiveTransitioning,通過查閱資料了解到,UIPercentDrivenInteractiveTransition這個類的對象會根據我們的手勢,來決定我們的自定義過渡的完成度,也就是這兩個其實是和手勢交互相關聯的,自然而然我們就想到了iOS 7引進的側滑手勢,對,就是側滑手勢,說到這里,我就順帶介紹一個類,UIScreenEdgePanGestureRecognizer,手勢側滑的類,具體怎么使用,后面我會陸續講到。

涉及函數

//更新進度
- (void)updateInteractiveTransition:(CGFloat)percentComplete;
//取消轉場 回到轉場前的效果
- (void)cancelInteractiveTransition;
//完成轉場 
- (void)finishInteractiveTransition;
UIViewControllerAnimatedTransitioning

在這個類中,我們又看到了兩個函數

//轉場時間
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext;

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;

其中又涉及到一個新的類UIViewControllerContextTransitioning,那么這個又是干什么的呢?我們等下再來了解,先來談談第一個函數transitionDuration,從返回值我們可以猜測出這是和時間有關的,沒錯,這就是我們自定義轉場動畫所需要的時間
那么下面我們就來看看UIViewControllerContextTransitioning

UIViewControllerContextTransitioning

這個類就是我們自定義轉場動畫所需要的核心,即轉場動畫的上下文,定義了轉場時需要的元素,比如在轉場過程中所參與的視圖控制器和視圖的相關屬性

//轉場動畫的容器
@property(nonatomic, readonly) UIView *containerView;
//通過對應的`key`可以得到我們需要的`vc`
- (UIViewController *)viewControllerForKey:(UITransitionContextViewControllerKey)key
//轉場動畫完成時候調用,必須調用,否則在進行其他轉場沒有任何效果
- (void)completeTransition:(BOOL)didComplete

看到這里,我們現在再去看UINavigationControllerDelegate 中的兩個函數和UIViewControllerAnimatedTransitioning 中的animateTransition 函數,就能完全理解了

//主要用於手勢交互轉場 for push or pop
- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                          interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController NS_AVAILABLE_IOS(7_0);

//非手勢交互轉場 for push or pop
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0);

//實現轉場動畫 通過transitionContext
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext;

到此,我們還有一個類沒有了解,那就是UIViewControllerTransitioningDelegate有了前面的分析,我們可以很好的理解

UIViewControllerTransitioningDelegate

主要是針對presentdismiss動畫的轉場

//非手勢轉場交互 for present
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
//非手勢轉場交互 for dismiss
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
//手勢交互 for dismiss
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator
//手勢交互 for present
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator

基本定義和概覽我們差不多應該有了一定的了解,正如上圖中的簡單描述。

了解性的東西說了這么多,下面我們就來點實際性的東西,除了第一張開門那種自定義動畫,再來幾個比較常用的動畫

CircleSpread.gif

circleRectSpread.gif

page.gif

這些動畫都比較簡單,相信許多大神都很清楚,還望見諒,下面我就對每一種進行分析分析,在分析動畫之前,先來看看怎么將上面的各個類進行封裝起來,使用更方便,這里不得不感謝很久之前看到的一篇文章,從他的文章中收獲非常大。

在學習轉場動畫的時候,雖然對所有類的關系有了一定了解,但是封裝的時候,完全沒有想到還有這么好的思路,確實是學習了。下面我們就一起來看看封裝思路。

封裝思路

1. 新建一個綜合管理轉場動畫的類

作用:主要是管理轉場所需要的一些設置,諸如轉場時間和轉場的實現(主要是在子類中進行實現,分離開來),用戶在自定義轉場動畫的時候,只需要繼承該類並重寫父類方法就可以
類名:GLTransitionManager,需要准守的協議有<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>
通過這樣,就可以將presentpush動畫相關的操作在該類中進行管理
GLTransitionManager.h中具體方法

@interface GLTransitionManager : NSObject<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>

/**
 轉場動畫的時間 默認為0.5s
 */
@property (nonatomic,assign) NSTimeInterval duration;

/**
 入場動畫 
 
 @param contextTransition 實現動畫
 */
- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition;


/**
 退場動畫
 
 @param contextTransition 實現動畫
 */
- (void)setBackAnimation:(id<UIViewControllerContextTransitioning>)contextTransition;

相信大家也看到了在入場和退場動畫中都有(id<UIViewControllerContextTransitioning>) contextTransition 這么一個參數,通過該參數,我們可以獲取轉場動畫的相關vc和其他信息,進行轉場動畫的實現,即我們在自定義轉場動畫的時候,只需要重寫該兩個方法就可以,通過contextTransition來實現動畫,而<UIViewControllerContextTransitioning>又在UIViewControllerAnimatedTransitioning協議的方法- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext中涉及到,於是我又新建了一個准守協議UIViewControllerAnimatedTransitioning的類GLTransitionAnimation,也就是下面我們將的類

2.轉場動畫配置及實現類

作用:雖然是配置和實現類,但是在該類中並沒有進行實現,這里也正是之前那個博主的高明之處,至少我是這么認為的。在該類中,我們用block的傳值方法將其傳入到我們的管理類中,也就是GLTransitionManager

GLTransitionAnimation.h文件

/**
 GLTransitionAnimation 塊

 @param contextTransition 將滿足UIViewControllerContextTransitioning協議的對象傳到管理內 在管理類對動畫統一實現
 */
typedef void(^GLTransitionAnimationBlock)(id <UIViewControllerContextTransitioning> contextTransition);

@interface GLTransitionAnimation : NSObject<UIViewControllerAnimatedTransitioning>

@property (nonatomic,copy) GLTransitionAnimationBlock animationBlock;

/**
 初始化方法

 @param duration 轉場時間
 @return 返回
 */
- (id)initWithDuration:(NSTimeInterval)duration;

GLTransitionAnimation.m文件比較簡單,這里就先不詳說,我們先回到管理類中,來看看怎么使用

GLTransitionManager.m文件,
在此種定義兩個屬性

/**
 入場動畫
 */
@property (nonatomic,strong) GLTransitionAnimation *toTransitionAnimation;

/**
 退場動畫
 */
@property (nonatomic,strong) GLTransitionAnimation *backTransitionAnimation;

實現方法

#pragma mark == 懶加載
- (GLTransitionAnimation *)toTransitionAnimation
{
    if (nil == _toTransitionAnimation) {
        __weak typeof(self) weakSelf = self;
        _toTransitionAnimation = [[GLTransitionAnimation alloc] initWithDuration:self.duration ];
        _toTransitionAnimation.animationBlock = ^(id<UIViewControllerContextTransitioning> contextTransition)
        {
            [weakSelf setToAnimation:contextTransition];
        };
    }
    return _toTransitionAnimation;
}

- (GLTransitionAnimation *)backTransitionAnimation
{
    if (nil == _backTransitionAnimation) {
        __weak typeof(self) weakSelf = self;
        _backTransitionAnimation = [[GLTransitionAnimation alloc] initWithDuration:self.duration];
        _backTransitionAnimation.animationBlock = ^(id<UIViewControllerContextTransitioning> contextTransition)
        {
            [weakSelf setBackAnimation:contextTransition];
        };
    }
    return _backTransitionAnimation;
}

通過上面這一方法,我們就很好的將關鍵參數和對外接口聯系起來了。這樣我們就只需要在setToAnimationsetBackAnimation進行轉場動畫的具體實現即可。
當然這里還有一個小問題,相信各位也發現了,就是為什么將屬性定義在了.m文件里呢?是的,這里確實是定義在了.m文件中,其實就是為了更少的暴露不需要的。

搞定這個之后,我們在來看看,在上面時候,調用該屬性呢?
下面我們就來看具體使用的地方

//非手勢轉場交互 for present
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return self.toTransitionAnimation;
}

//非手勢轉場交互 for dismiss
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return self.backTransitionAnimation;
}

//================
//非手勢轉場交互 for push or pop
/*****注釋:通過 fromVC 和 toVC 我們可以在此設置需要自定義動畫的類 *****/
- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC
{
    _operation = operation;
    
    if (operation == UINavigationControllerOperationPush)
    {
        return self.toTransitionAnimation;
    }
    else if (operation == UINavigationControllerOperationPop)
    {
        return self.backTransitionAnimation;
    }
    else
    {
        return nil;
    }
}

在這兩個地方使用后,我們差不多就完成了一半了,那還一部分呢?那就是我們的手勢滑動,下面我們就來看看手勢滑動。

3.手勢交互管理類

作用:主要通過側滑手勢來管理交互,在iOS 7后引入新的類UIPercentDrivenInteractiveTransition,該類的對象會根據我們的手勢,來決定我們的自定義過渡的完成度,所以此次我采用繼承的方式,然后在繼承的類中加入滑動手勢類,這里加入的是側滑手勢類UIScreenEdgePanGestureRecognizer,這個類也就是我定義的GLInteractiveTransition

GLInteractiveTransition.h文件


/**
 手勢的方向枚舉

 - GLPanEdgeTop:屏幕上方
 - GLPanEdgeLeft:屏幕左側
 - GLPanEdgeBottom: 屏幕下方
 - GLPanEdgeRight: 屏幕右方
 */
typedef NS_ENUM(NSInteger,GLEdgePanGestureDirection) {
    GLPanEdgeTop    = 0,
    GLPanEdgeLeft,
    GLPanEdgeBottom,
    GLPanEdgeRight
};


///**
// 手勢轉場類型
//
// - GLInteractiveTransitionPush: push
// - GLInteractiveTransitionPop: pop
// - GLInteractiveTransitionPresent: present
// - GLInteractiveTransitionDismiss: dismiss
// */
//typedef NS_ENUM(NSInteger,GLInteractiveTransitionType) {
//    GLInteractiveTransitionPush = 0,
//    GLInteractiveTransitionPop,
//    GLInteractiveTransitionPresent ,
//    GLInteractiveTransitionDismiss
//};


@interface GLInteractiveTransition : UIPercentDrivenInteractiveTransition

/**
 是否滿足側滑手勢交互
 */
@property (nonatomic,assign) BOOL isPanGestureInteration;


/**
 轉場時的操作 不用傳參數的block
 */
@property (nonatomic,copy) dispatch_block_t eventBlcok;

/**
 添加側滑手勢

 @param view 添加手勢的view
 @param direction 手勢的方向
 */
- (void)addEdgePageGestureWithView:(UIView *)view direction:(GLEdgePanGestureDirection)direction;

.h文件中,定義了兩個屬性,一個是用來判斷是否需滿足側滑手勢,這個在后面會講到。另一個是用來在側滑的時候執行所需要的轉場的block,之前本來是沒有加這個的,但是在后面使用的時候,由於想加側滑的presentpush效果,所以就加了一個。

下面看看.m文件滑動手勢中的具體實現

- (void)handlePopRecognizer:(UIPanGestureRecognizer*)recognizer {
    // 計算用戶手指划了多遠
    
    CGFloat progress = fabs([recognizer translationInView:self.gestureView].x) / (self.gestureView.bounds.size.width * 1.0);
    progress = MIN(1.0, MAX(0.0, progress));
        
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
        {
            _isPanGestureInteration = YES;
            
            if (self.eventBlcok) {
                self.eventBlcok();
            }
            
            // 創建過渡對象,彈出viewController
//            
//            UIViewController *fromVc = [self gl_viewController];
//            
//            switch (self.transitionType) {
//                case GLInteractiveTransitionPush:
//                {
//                    
//                }
//                    break;
//                case GLInteractiveTransitionPop:
//                {
//                    if (fromVc.navigationController) {
//                        [fromVc.navigationController popViewControllerAnimated:YES];
//                    }
//                }
//                    break;
//                case GLInteractiveTransitionPresent:
//                {
//                    
//                }
//                    break;
//                case GLInteractiveTransitionDismiss:
//                {
//                    [fromVc dismissViewControllerAnimated:YES completion:nil];
//                }
//                    break;
//                default:
//                    break;
//            }
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            // 更新 interactive transition 的進度
            [self updateInteractiveTransition:progress];
            break;
        }
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        {
//            NSLog(@" 打印信息:%f",progress);
            // 完成或者取消過渡
            if (progress > 0.5) {
                [self finishInteractiveTransition];
            }
            else {
                [self cancelInteractiveTransition];
            }
            
            _isPanGestureInteration = NO;
            break;
        }
        default:
            break;
    }
}

手勢交互管理類的核心代碼差不多就這么多,下面我們看看怎么使用

4.UIViewController + GLTransition

為了和系統的轉場動畫的函數區分開來,這里我新建了一個UIViewControllercategoryUIViewController + GLTransition,在其中定義了四個函數,分別如下

/**
 push動畫

 @param viewController 被push viewController
 @param transitionManager 控制類
 */
- (void)gl_pushViewControler:(UIViewController *)viewController withAnimation:(GLTransitionManager*)transitionManager;


/**
 present動畫

 @param viewController 被present viewController
 @param transitionManager 控制類
 */
- (void)gl_presentViewControler:(UIViewController *)viewController withAnimation:(GLTransitionManager*)transitionManager;


/**
 注冊入場手勢

 @param direction 方向
 @param blcok 手勢轉場觸發的點擊事件
 */
- (void)gl_registerToInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok;

/**
 注冊返回手勢

 @param direction 側滑方向
 @param blcok 手勢轉場觸發的點擊事件
 */
- (void)gl_registerBackInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok;

下面我們看看具體實現
UIViewController (GLTransition).m文件

- (void)gl_pushViewControler:(UIViewController *)viewController withAnimation:(GLTransitionManager *)transitionManager
{
    if (!viewController) {
        return;
    }
    if (!transitionManager) {
        return;
    }
    
    if (self.navigationController) {
        
        self.navigationController.delegate = transitionManager;
        
        GLInteractiveTransition *toInteractiveTransition = objc_getAssociatedObject(self, &kToAnimationKey);
        if (toInteractiveTransition) {
            [transitionManager setValue:toInteractiveTransition forKey:@"toInteractiveTransition"];
        }
        
        objc_setAssociatedObject(viewController, &kAnimationKey, transitionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [self.navigationController pushViewController:viewController animated:YES];
   
    }
}

- (void)gl_presentViewControler:(UIViewController *)viewController withAnimation:(GLTransitionManager *)transitionManager
{
    if (!viewController) {
        return;
    }
    if (!transitionManager) {
        return;
    }
    //present 動畫代理 被執行動畫的vc設置代理
    viewController.transitioningDelegate = transitionManager;
    
    GLInteractiveTransition *toInteractiveTransition = objc_getAssociatedObject(self, &kToAnimationKey);
    if (toInteractiveTransition) {
        [transitionManager setValue:toInteractiveTransition forKey:@"toInteractiveTransition"];
    }
    objc_setAssociatedObject(viewController, &kAnimationKey, transitionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    [self presentViewController:viewController animated:YES completion:nil];
}

- (void)gl_registerToInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok
{
    GLInteractiveTransition *interactiveTransition = [[GLInteractiveTransition alloc] init];
    interactiveTransition.eventBlcok = blcok;
    [interactiveTransition addEdgePageGestureWithView:self.view direction:direction];
    
    objc_setAssociatedObject(self, &kToAnimationKey, interactiveTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)gl_registerBackInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok
{
    GLInteractiveTransition *interactiveTransition = [[GLInteractiveTransition alloc] init];
    interactiveTransition.eventBlcok = blcok;
    [interactiveTransition addEdgePageGestureWithView:self.view direction:direction];
    
    //判讀是否需要返回 然后添加側滑
    GLTransitionManager *animator = objc_getAssociatedObject(self, &kAnimationKey);
    if (animator)
    {
        //用kvc的模式  給 animator的backInteractiveTransition 退場賦值
        [animator setValue:interactiveTransition forKey:@"backInteractiveTransition"];
    }
}

pushpresent中,有幾個需要注意的地方
1、self.navigationController.delegate = transitionManager
2、viewController.transitioningDelegate = transitionManager
上面兩個主要是將navigationController的代理和viewControllertransitioningDelegate指向對象transitionManager,這個對象是准守了<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate>兩個協議的,這樣我們就能夠在pushpresent的時候,簡單的去調協議方法。

3、設置手勢交互轉場

        GLInteractiveTransition *toInteractiveTransition = objc_getAssociatedObject(self, &kToAnimationKey);
        if (toInteractiveTransition) {
            [transitionManager setValue:toInteractiveTransition forKey:@"toInteractiveTransition"];
        }

pushpresent方法中,都有這樣的代碼,這里為了減少不必要的暴露,在GLTransitionManager.m文件中,我還定義了兩個屬性

/**
 入場手勢
 */
@property (nonatomic,strong) GLInteractiveTransition *toInteractiveTransition;

/**
 退場手勢
 */
@property (nonatomic,strong) GLInteractiveTransition *backInteractiveTransition;

並且通過kvc的方式對其進行賦值,當轉場動畫進行的時候,會先去調用非轉場動畫的方法,比如push的時候,會先調用

- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC

然后再調用手勢交互

//手勢交互 for push or pop
- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController

這個時候,我們就需要加一個判斷,也就是通過GLInteractiveTransition類中的是否滿足側滑手勢交互isPanGestureInteration這個屬性來判斷,前面在側滑手勢剛剛進行的時候,就對其進行了賦值,並設置為yes,對應的實現代碼就是

- (id<UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController
{
    if (_operation == UINavigationControllerOperationPush) {
        return self.toInteractiveTransition.isPanGestureInteration ? self.toInteractiveTransition:nil;
    }
    else{
        return self.backInteractiveTransition.isPanGestureInteration ? self.backInteractiveTransition:nil;
    }
}

如果返回的為nil,那么就不會去調用手勢交互類,否則則會調用。同理,present的時候也是一樣
所以就有了下面的代碼

//手勢交互 for dismiss
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator{
    return self.backInteractiveTransition.isPanGestureInteration ? self.backInteractiveTransition:nil;
}

//手勢交互 for present
- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator{
   return self.toInteractiveTransition.isPanGestureInteration ? self.toInteractiveTransition:nil;
}

UIViewController + GLTransition中的pushpresent函數中,還有一個需要注意的地方,那就是

objc_setAssociatedObject(viewController, &kAnimationKey, transitionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

這里通過runtime的方式給vc設置了一個屬性值,為什么這么做呢?因為在arc下,如果我們在使用GLTransitionManager的時候去創建一個對象而非vc的屬性,那么在push的時候GLTransitionManager這個對象就會被系統釋放掉,這樣我們后面所有有關轉場的操作就不能再實現了,或許我們可以給vc建一個base類,然后添加一個GLTransitionManager對象的屬性,但是這樣或許有點復雜,所有這里就這樣處理了。

UIViewController + GLTransition中還有兩個函數的實現,其原理,我相信大家應該都能看明白了,就不再詳細說明了

- (void)gl_registerToInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok
{
    GLInteractiveTransition *interactiveTransition = [[GLInteractiveTransition alloc] init];
    interactiveTransition.eventBlcok = blcok;
    [interactiveTransition addEdgePageGestureWithView:self.view direction:direction];
    
    objc_setAssociatedObject(self, &kToAnimationKey, interactiveTransition, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)gl_registerBackInteractiveTransitionWithDirection:(GLEdgePanGestureDirection)direction eventBlcok:(dispatch_block_t)blcok
{
    GLInteractiveTransition *interactiveTransition = [[GLInteractiveTransition alloc] init];
    interactiveTransition.eventBlcok = blcok;
    [interactiveTransition addEdgePageGestureWithView:self.view direction:direction];
    
    //判讀是否需要返回 然后添加側滑
    GLTransitionManager *animator = objc_getAssociatedObject(self, &kAnimationKey);
    if (animator)
    {
        //用kvc的模式  給 animator的backInteractiveTransition 退場賦值
        [animator setValue:interactiveTransition forKey:@"backInteractiveTransition"];
    }
}

整個封裝的思路差不多到這里就完了,希望對大家有用

文章有點長,希望大家能夠理解,因為后面還有。。。。

幾個動畫的具體實現

1、開門動畫

由於我們已經有了基類``,所以當我們需要實現什么動畫的時候,只需要集成該類就可以了

針對開門動畫我新建了下面這么一個類GLTransitionManager

@interface GLOpenDoorAnimation : GLTransitionManager

@end

然后在重新父類的方法

- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition

具體實現
1、根據id<UIViewControllerContextTransitioning>對象先得到幾個關鍵值,目標vc和當前vc和容器containerView

    //獲取目標動畫的VC
    UIViewController *toVc = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVc = [contextTransition viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *containerView = [contextTransition containerView];

2、由於是開門動畫,所以其過程大概是這樣的:當前vc逐漸縮小,目標vc慢慢從屏幕兩邊移到中間,但是我們又不能把目標vcview分成兩個部分,所以這里我們可以利用截圖,來給用戶造成一個假象。先截兩個圖,然后分別讓其坐標居於屏幕外,然后用動畫讓其慢慢移動到屏幕中間,動畫完成的時候,移除當前兩個截圖。這里有個小問題,那就是當前vc的縮放,雖然我們能夠使其縮小,但是這樣,如果涉及到側滑手勢的話,問題就來了。因為view的寬發生了變化,這樣我們根據寬度來計算滑動的距離,從而更新轉場動畫的時候就會出現問題,導致

- (void)handlePopRecognizer:(UIPanGestureRecognizer*)recognizer {
    // 計算用戶手指划了多遠
    
    CGFloat progress = fabs([recognizer translationInView:self.gestureView].x) / (self.gestureView.bounds.size.width * 1.0);
    progress = MIN(1.0, MAX(0.0, progress));

中的progress 出現問題。所以這里也就采用了截圖的方式,對該截圖進行縮放,而不去修改vcview

下面看下核心代碼

- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    //獲取目標動畫的VC
    UIViewController *toVc = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVc = [contextTransition viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *containerView = [contextTransition containerView];
    
    UIView *fromView = fromVc.view;
    UIView *toView = toVc.view;
    
    //截圖
    UIView *toView_snapView = [toView snapshotViewAfterScreenUpdates:YES];
    
    CGRect left_frame = CGRectMake(0, 0, CGRectGetWidth(fromView.frame) / 2.0, CGRectGetHeight(fromView.frame));
    CGRect right_frame = CGRectMake(CGRectGetWidth(fromView.frame) / 2.0, 0, CGRectGetWidth(fromView.frame) / 2.0, CGRectGetHeight(fromView.frame));
    UIView *from_left_snapView = [fromView resizableSnapshotViewFromRect:left_frame
                                                         afterScreenUpdates:NO
                                                              withCapInsets:UIEdgeInsetsZero];
    
    UIView *from_right_snapView = [fromView resizableSnapshotViewFromRect:right_frame
                                                         afterScreenUpdates:NO
                                                              withCapInsets:UIEdgeInsetsZero];
    
    toView_snapView.layer.transform = CATransform3DMakeScale(0.7, 0.7, 1);
    from_left_snapView.frame = left_frame;
    from_right_snapView.frame = right_frame;
    
    //將截圖添加到 containerView 上
    [containerView addSubview:toView_snapView];
    [containerView addSubview:from_left_snapView];
    [containerView addSubview:from_right_snapView];
    
    fromView.hidden = YES;
    
    [UIView animateWithDuration:self.duration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        //左移
        from_left_snapView.frame = CGRectOffset(from_left_snapView.frame, -from_left_snapView.frame.size.width, 0);
        //右移
        from_right_snapView.frame = CGRectOffset(from_right_snapView.frame, from_right_snapView.frame.size.width, 0);
        
        toView_snapView.layer.transform = CATransform3DIdentity;
        
    } completion:^(BOOL finished) {
        fromView.hidden = NO;
        
        [from_left_snapView removeFromSuperview];
        [from_right_snapView removeFromSuperview];
        [toView_snapView removeFromSuperview];
        
        if ([contextTransition transitionWasCancelled]) {
            [containerView addSubview:fromView];
        } else {
            [containerView addSubview:toView];
        }
        [contextTransition completeTransition:![contextTransition transitionWasCancelled]];
    }];
}

setBackAnimation動畫和上面的大同小異,就不再詳細說明,文章后面有demo地址,大家可以看看。

2、圓圈逐漸放大轉場動畫

在做動畫之前,我們先要了解其大概原理
這里我簡單的做了個草圖

Paste_Image.png
小圓和大圓分別表示動畫前和動畫后
這里我們采用的是UIBezierPath + mask + CAShapeLayer的策略對其進行實習

大家都知道,UIBezierPath可以畫圓形,而CAShapeLayer又具備CGPathRef path屬性,可以和UIBezierPath聯系起來,而UIView又具備CALayer *mask屬性,這樣三者就這么巧妙的聯系起來了。
在這里,我們使用CABasicAnimation動畫,通過對其設置[CABasicAnimation animationWithKeyPath:@"path"]來讓其執行我們想要的path路徑動畫
於是就有了下面的代碼

- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    //獲取目標動畫的VC
    UIViewController *toVc = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [contextTransition containerView];
    [containerView addSubview:toVc.view];
    
    //創建UIBezierPath路徑 作為后面動畫的起始路徑
    UIBezierPath *startPath = [UIBezierPath bezierPathWithArcCenter:self.centerPoint radius:self.radius startAngle:0 endAngle:2*M_PI clockwise:YES];
    
    //創建結束UIBezierPath
    //首先我們需要得到后面路徑的半徑  半徑應該是距四個角最遠的距離
    CGFloat x = self.centerPoint.x;
    CGFloat y = self.centerPoint.y;
    //取出其中距屏幕最遠的距離 來求圍城矩形的對角線 即我們所需要的半徑
    CGFloat radius_x = MAX(x, containerView.frame.size.width - x);
    CGFloat radius_y = MAX(y, containerView.frame.size.height - y);
    //補充下 sqrtf求平方根   double pow(double x, double y); 求 x 的 y 次冪(次方)
    //通過勾股定理算出半徑
    CGFloat endRadius = sqrtf(pow(radius_x, 2) + pow(radius_y, 2));
    
    UIBezierPath *endPath = [UIBezierPath bezierPathWithArcCenter:self.centerPoint radius:endRadius startAngle:0 endAngle:2*M_PI clockwise:YES];
    
//    self.endPath = endPath;
    
    //創建CAShapeLayer 用以后面的動畫
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = endPath.CGPath;
    toVc.view.layer.mask = shapeLayer;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.fromValue = (__bridge id _Nullable)(startPath.CGPath);
    animation.duration = self.duration;
    animation.delegate = (id)self;
//    animation.removedOnCompletion = NO;//執行后移除動畫
    //保存contextTransition  后面動畫結束的時候調用
    [animation setValue:contextTransition forKey:@"pathContextTransition"];
    [shapeLayer addAnimation:animation forKey:nil];
    
    self.maskShapeLayer = shapeLayer;
}

由於代碼中有比較詳細的說明,所以這里就不再詳細說明,setBackAnimation也大同小異

3、圓圈和目標vc共同縮放轉場動畫

這個比較簡單,主要是利用UIView的縮放進行的,由於目標vc的上角和圓是相切的,所以,這里我們可以先假設目標vc處於正常狀態,然后再跟進小圓的中心,畫一個大圓,讓其和目標vc一起縮放就是。這里留了一個缺陷,那就是不支持側滑,因為我是用目標vc進行縮放的,而沒有截圖,大家可以試試。
其實現大概為

- (CGRect)frameToCircle:(CGPoint)centerPoint size:(CGSize)size
{
    CGFloat radius_x = fmax(centerPoint.x, size.width - centerPoint.x);
    CGFloat radius_y = fmax(centerPoint.y, size.height - centerPoint.y);
    CGFloat endRadius = 2 * sqrtf(pow(radius_x, 2) + pow(radius_y, 2));

    CGRect rect = {CGPointZero,CGSizeMake(endRadius, endRadius)};
    
    return rect;
}


- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    //獲取目標動畫的VC
    UIViewController *toVc = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [contextTransition containerView];
    
//    [toVc beginAppearanceTransition:YES animated:YES];
    CGPoint center = toVc.view.center;
    
    CGRect rect = [self frameToCircle:self.centerPoint size:toVc.view.bounds.size];
    UIView *backView = [[UIView alloc] initWithFrame:rect];
    backView.backgroundColor = UICOLOR_FROM_RGB_OxFF(0xFFA500);
    backView.center = self.centerPoint;
    backView.layer.cornerRadius = backView.frame.size.height / 2.0;
    backView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [containerView addSubview:backView];
    
    self.startView = backView;
    
    toVc.view.transform = CGAffineTransformMakeScale(0.01, 0.01);
    toVc.view.alpha = 0;
    toVc.view.center = self.centerPoint;
    [containerView addSubview:toVc.view];
    
    
    [UIView animateWithDuration:self.duration animations:^{
        
        backView.transform = CGAffineTransformIdentity;
        
        toVc.view.center = center;
        toVc.view.transform = CGAffineTransformIdentity;
        toVc.view.alpha = 1;
        
    } completion:^(BOOL finished) {
        [contextTransition completeTransition:!contextTransition.transitionWasCancelled];
        
//        [toVc endAppearanceTransition];
    }];
}

setBackAnimation也大同小異,就不再說明

4、翻書效果

這個還是花了些時間,主要不在思想上,而是在翻書有個陰影效果哪里,等下我會講到。先說說思路,主要還是通過截圖來實現。首先需要截當前vc的部分,如果向左滑則截右邊,向右則截左,然后還需要截目標vc的兩部分圖,分別加到containerView上,假如現在向左翻,那么就要將目標vc的左邊截圖加到containerView的左邊並且隱藏起來,讓其繞y軸旋轉M_PI_2,就是直插屏幕的樣子,那么目標vc的右邊截圖就需要放到當前vc的下面,這樣當當前vc在滑動的時候,我們就能看到下面的圖了。當當前vcy軸旋轉-M_PI_2的時候,目標vc的左邊截圖顯示出來,並恢復原狀,完成整副動畫。
需要注意的是,截圖在繞y軸旋轉的時候,因為我們的layer的默認anchorPoint(0.5,0.5),所以需要改變anchorPoint的只,否則就繞中心在旋轉了。

說了這么多,還是看看核心代碼吧

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #3d71ff}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #4dbf56}p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #00afca}p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #3d71ff; min-height: 16.0px}p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #2337da}p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'PingFang SC'; color: #4dbf56}span.s1 {font-variant-ligatures: no-common-ligatures}span.s2 {font-variant-ligatures: no-common-ligatures; color: #c2349b}span.s3 {font-variant-ligatures: no-common-ligatures; color: #00afca}span.s4 {font-variant-ligatures: no-common-ligatures; color: #3d71ff}span.s5 {font: 14.0px 'PingFang SC'; font-variant-ligatures: no-common-ligatures}span.s6 {font-variant-ligatures: no-common-ligatures; color: #4dbf56}span.s7 {font: 14.0px 'PingFang SC'; font-variant-ligatures: no-common-ligatures; color: #4dbf56}span.s8 {font: 14.0px Menlo; font-variant-ligatures: no-common-ligatures; color: #2337da}span.s9 {font: 14.0px Menlo; font-variant-ligatures: no-common-ligatures; color: #3d71ff}span.s10 {font: 14.0px Menlo; font-variant-ligatures: no-common-ligatures}span.s11 {font-variant-ligatures: no-common-ligatures; color: #8b84cf}span.s12 {font-variant-ligatures: no-common-ligatures; color: #93c96a}span.s13 {font-variant-ligatures: no-common-ligatures; color: #d28f5a}

- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    //獲取目標動畫的VC
    UIViewController *toVc = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController *fromVc = [contextTransition viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIView *containerView = [contextTransition containerView];
    
    //m34 這個參數有點不好理解  為透視效果 我在http://www.jianshu.com/p/e8d1985dccec這里有講
    //當Z軸上有變化的時候 我們所看到的透視效果 可以對比看看 當你改成-0.1的時候 就懂了
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = -0.002;
    [containerView.layer setSublayerTransform:transform];
    
    UIView *fromView = fromVc.view;
    UIView *toView = toVc.view;
    
    //截圖
    //當前頁面的右側
    CGRect from_half_right_rect = CGRectMake(fromView.frame.size.width/2.0, 0, fromView.frame.size.width/2.0, fromView.frame.size.height);
    //目標頁面的左側
    CGRect to_half_left_rect = CGRectMake(0, 0, toView.frame.size.width/2.0, toView.frame.size.height);
    //目標頁面的右側
    CGRect to_half_right_rect = CGRectMake(toView.frame.size.width/2.0, 0, toView.frame.size.width/2.0, toView.frame.size.height);
    
    //截三張圖 當前頁面的右側 目標頁面的左和右
    UIView *fromRightSnapView = [fromView resizableSnapshotViewFromRect:from_half_right_rect afterScreenUpdates:NO withCapInsets:UIEdgeInsetsZero];
    UIView *toLeftSnapView = [toView resizableSnapshotViewFromRect:to_half_left_rect afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero];
    UIView *toRightSnapView = [toView resizableSnapshotViewFromRect:to_half_right_rect afterScreenUpdates:YES withCapInsets:UIEdgeInsetsZero];
    
    
    fromRightSnapView.frame = from_half_right_rect;
    toLeftSnapView.frame = to_half_left_rect;
    toRightSnapView.frame = to_half_right_rect;
    
    //重新設置anchorPoint  分別繞自己的最左和最右旋轉
    fromRightSnapView.layer.position = CGPointMake(CGRectGetMinX(fromRightSnapView.frame), CGRectGetMinY(fromRightSnapView.frame) + CGRectGetHeight(fromRightSnapView.frame) * 0.5);
    fromRightSnapView.layer.anchorPoint = CGPointMake(0, 0.5);
    
    toLeftSnapView.layer.position = CGPointMake(CGRectGetMinX(toLeftSnapView.frame) + CGRectGetWidth(toLeftSnapView.frame), CGRectGetMinY(toLeftSnapView.frame) + CGRectGetHeight(toLeftSnapView.frame) * 0.5);
    toLeftSnapView.layer.anchorPoint = CGPointMake(1, 0.5);
    
    //添加陰影效果

    UIView *fromRightShadowView = [self addShadowView:fromRightSnapView startPoint:CGPointMake(0, 1) endPoint:CGPointMake(1, 1)];
    UIView *toLeftShaDowView = [self addShadowView:toLeftSnapView startPoint:CGPointMake(1, 1) endPoint:CGPointMake(0, 1)];
    
    //添加視圖  注意順序
    [containerView insertSubview:toView atIndex:0];
    [containerView addSubview:toLeftSnapView];
    [containerView addSubview:toRightSnapView];
    [containerView addSubview:fromRightSnapView];

    toLeftSnapView.hidden = YES;
    
    
    //先旋轉到最中間的位置
    toLeftSnapView.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 1, 0);
    //StartTime 和 relativeDuration 均為百分百
    [UIView animateKeyframesWithDuration:self.duration delay:0 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:0.5 animations:^{
            
            fromRightSnapView.layer.transform = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);
            fromRightShadowView.alpha = 1.0;
        }];
        
        [UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.5 animations:^{
            toLeftSnapView.hidden = NO;
            toLeftSnapView.layer.transform = CATransform3DIdentity;
            toLeftShaDowView.alpha = 0.0;
        }];
    } completion:^(BOOL finished) {
        [toLeftSnapView removeFromSuperview];
        [toRightSnapView removeFromSuperview];
        [fromRightSnapView removeFromSuperview];
        [fromView removeFromSuperview];
        
        if ([contextTransition transitionWasCancelled]) {
            [containerView addSubview:fromView];
        }
        
        [contextTransition completeTransition:![contextTransition transitionWasCancelled]];
    }];
    
    
    
//本來打算用基礎動畫來實現 但是由於需要保存幾個變量 在動畫完成的代理函數中用,所以就取消這個想法了
//    CABasicAnimation *fromRightAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
//    fromRightAnimation.duration = self.duration/2.0;
//    fromRightAnimation.beginTime = CACurrentMediaTime();
//    fromRightAnimation.toValue = @(-M_PI_2);
//    [fromRightSnapView.layer addAnimation:fromRightAnimation forKey:nil];
//    
//    
//    CABasicAnimation *toLeftAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
//    toLeftAnimation.beginTime = CACurrentMediaTime() + self.duration/2.0;
//    toLeftAnimation.fromValue = @(M_PI_2);
//    [toLeftAnimation setValue:contextTransition forKey:@"contextTransition"];
//    [toLeftSnapView.layer addAnimation:toLeftAnimation forKey:@"toLeftAnimation"];
}
項目文件截圖:


寫到這里,差不多轉場動畫我能夠寫的就到這里了,文章實在是有點長,不是故意為之,只是我想寫的稍微詳細點,對自己也是一個很好的提升。如果能幫到你,還請給個打賞,嘿嘿~
如果有什么不對的地方,還請多多指教,共同成長。
iOS 自定義轉場動畫淺談

代碼地址如下:
http://www.demodashi.com/demo/11612.html

注:本文著作權歸作者,由demo大師代發,拒絕轉載,轉載需要作者授權


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM