iOS自定义转场(custom transition)

    iOS中,从一个也没切换到另一个页面的效果叫转场(transition)。UINavgationController、UIViewController默认的转场效果有时不能满足项目的要求,需要我们创造新的效果,这就需要用到自定义转场啦!

    iOS自定义转场(custom transition)_第1张图片

    自定义的步骤:

    1、准备两个UIViewController,通常是从presentdingViewController(简写presenting)跳转到 presentedViewController(简写presented);

    2、presenteing中需要实现<UIViewControllerTransitioningDelegate>接口,然后重写该接口中的方法animationControllerForPresentedController、animationControllerForDismissedController。如果presentingVC中调用了[self presentViewController:  ],则会执行接口中的方法,这个方法就会返回自定义转场的效果;

    3、第二步中animationControllerForPresentedController方法应该返回转场动画的对象,它实现了<UIViewControllerAnimatedTransitioning>接口。该接口只有两个方法,transitionDuration和animateTransition,通过animateTransition就能让页面切换时,随心所欲的动起来。


    步骤2的代码:

#pragma mark UIViewControllerTransitioningDelegate
- (id)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{

    return [BPTransitionAnimator new];
//    return [[BPPresentaionController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
}

- (id)animationControllerForDismissedController:(UIViewController *)dismissed {
    
    return [BPTransitionAnimator new];
}

    步骤3的代码:

//
//  BPTransitionAnimator.m
//  Demo
//
//  Created by bingcai on 16/4/18.
//  Copyright © 2016年 Linda. All rights reserved.
//

#import "BPTransitionAnimator.h"

@implementation BPTransitionAnimator

- (NSTimeInterval)transitionDuration:(id)transitionContext{
    
    return 1.0;
}

- (void)animateTransition:(id)transitionContext{
    
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    fromView.frame = [transitionContext initialFrameForViewController:fromViewController];
    toView.frame = [transitionContext finalFrameForViewController:toViewController];
    
    fromView.alpha = 1.0;
    toView.alpha = 0.0;
    
    [containerView addSubview:toView];
    
    NSTimeInterval transitionDuration = [self transitionDuration:transitionContext];
    
    [UIView animateWithDuration:transitionDuration animations:^{
    
        fromView.alpha = 0.0;
        toView.alpha = 1.0;
        
    } completion:^(BOOL finished){
    
        BOOL isCancelled = [transitionContext transitionWasCancelled];
        [transitionContext completeTransition:!isCancelled];
    }];
}

@end


Demo下载

    

上述的方法都是支持iOS7的,但在使用的时候可能会用到iOS8的方法,需要注意。



你可能感兴趣的:(iOS)