iOS 自定义转场动画初探

      最近项目刚迭代,正好闲下来捣鼓了一下iOS的自定义转场的效果。闲话不多说,直接开始上代码吧。(ps:请忽略实际的转场效果,关注技术本身呢哦。pps:主要是转场的动画做的比较low啦!)

1、首先定义一个转场动画的类

      第一步,咱们先定义一个管理转场动画的类。首先创建一个继承自NSObject的类,这里叫JTAnimatedTransition,并且让其遵循UIViewControllerAnimatedTransitioning这个协议。
      这个是.h文件代码。 我在这里定义了一个枚举,用来表示转场的类型。并且还遵循的CAAnimationDelegate协议,这个后面会说到。 再有呢,就是一个类方法了,这个是在使用的控制器中会用到的方法,具体的用法后续代码中会有体现。

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef enum {
    JTAnimatedTransitionTypePush,
    JTAnimatedTransitionTypePop,
    JTAnimatedTransitionTypePresent,
    JTAnimatedTransitionTypeDismiss
}JTAnimatedTransitionType;

@interface JTAnimatedTransition : NSObject<UIViewControllerAnimatedTransitioning, CAAnimationDelegate>
@property (assign, nonatomic) JTAnimatedTransitionType type;
@property (strong, nonatomic) id transitionContext;
+ (JTAnimatedTransition *)animatedTransitionWithType:(JTAnimatedTransitionType)type;
@end

接下来是.m中的代码了。 具体说明在代码中都有详细注释。

#import "JTAnimatedTransition.h"
@implementation JTAnimatedTransition

+ (JTAnimatedTransition *)animatedTransitionWithType:(JTAnimatedTransitionType)type
{
    JTAnimatedTransition *animatedTransition = [[JTAnimatedTransition alloc] init];
    animatedTransition.type = type;
    return animatedTransition;
}


#pragma mark - UIViewControllerAnimatedTransitioning
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    //返回动画执行的时间
    return 0.5;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
    //在这里设置自己想要的动画效果
    self.transitionContext = transitionContext;
    
    if (self.type == JTAnimatedTransitionTypePush) {
        
        // 获得即将消失的vc的v
        UIView *fromeView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        // 获得即将出现的vc的v
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        // 获得容器view
        UIView *containerView = [transitionContext containerView];
        
        [containerView addSubview:fromeView];
        [containerView addSubview:toView];
        
        UIBezierPath *startBP = [UIBezierPath bezierPathWithOvalInRect:CGRectMake((containerView.frame.size.width-100)/2, 100, 100, 100)];
        CGFloat radius = 1000;
        UIBezierPath *finalBP = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(150 - radius, 150 -radius, radius*2, radius*2)];
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = finalBP.CGPath;
        toView.layer.mask = maskLayer;
        
        //执行动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
        animation.delegate = self;
        animation.fromValue = (__bridge id _Nullable)(startBP.CGPath);
        animation.toValue = (__bridge id _Nullable)(finalBP.CGPath);
        animation.duration = [self transitionDuration:transitionContext];
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [maskLayer addAnimation:animation forKey:@"path"];
        
    } else if (self.type == JTAnimatedTransitionTypePresent) {
        
        UIView *fromeView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        UIView *containerView = [transitionContext containerView];
        
        [containerView addSubview:fromeView];
        [containerView addSubview:toView];
        
        fromeView.frame = containerView.frame;
        toView.frame = containerView.frame;
        
        toView.layer.anchorPoint = CGPointMake(0.0f, 1.0f);
        toView.frame = containerView.frame;
        toView.transform = CGAffineTransformMakeRotation(-M_PI/2);
        
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            toView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self.transitionContext completeTransition:YES];
        }];
        
    } else if (self.type == JTAnimatedTransitionTypeDismiss) {
        
        UIView *fromeView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
        UIView *containerView = [transitionContext containerView];
        
        [containerView addSubview:fromeView];
        [containerView addSubview:toView];
        
        fromeView.frame = containerView.frame;
        toView.frame = CGRectMake(containerView.frame.size.width, containerView.frame.origin.y, 0, containerView.frame.size.height);
        
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            fromeView.frame = CGRectMake(containerView.frame.origin.x, containerView.frame.origin.y, 0, containerView.frame.size.height);
            toView.frame = containerView.frame;
        } completion:^(BOOL finished) {
            [self.transitionContext completeTransition:YES];
        }];
        
    } else {
    }
}

#pragma mark - CAAnimationDelegate
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    //告诉系统转场动画完成
    [self.transitionContext completeTransition:YES];
    
    //清除相应控制器视图的mask
    [self.transitionContext viewForKey:UITransitionContextFromViewKey].layer.mask = nil;
    [self.transitionContext viewForKey:UITransitionContextToViewKey].layer.mask = nil;
}

@end

到这里转场动画管理者就写好了,后面我们只需要关注使用者的情况了。

2、怎么使用转场动画

      现在我们创建一个使用者类。我这里就直接使用了ViewController了。下面是创建好之后的效果图。

首页.png

下面就是.m的具体实现代码了,一些简单的界面搭建代码就不贴出来了。下面的代码只是一些跟转场动画有关的代码哦。

这是点击cell之后的逻辑
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ViewControllerTwo *vc = [[ViewControllerTwo alloc]init];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    CGRect rectInTableView = [tableView rectForRowAtIndexPath:indexPath];
    CGRect rect = [tableView convertRect:rectInTableView toView:[tableView superview]];
    cell.imageView.hidden = YES;
    self.selectImageView.image = cell.imageView.image;
    self.selectImageView.frame = CGRectMake(cell.imageView.frame.origin.x, rect.origin.y, cell.imageView.frame.size.width, cell.imageView.frame.size.height);

    vc.img = self.selectImageView.image;
    vc.row = indexPath.row;
    [UIView animateWithDuration:0.5 animations:^{
        self.selectImageView.frame = CGRectMake(0, 2, self.view.bounds.size.width/2, self.view.bounds.size.width/2);
        self.selectImageView.center = CGPointMake(self.view.bounds.size.width/2, 200);
    } completion:^(BOOL finished) {
    [self.navigationController pushViewController:vc animated:YES];
        }];
}

要实现自定义的转场,还需要使用者必须遵循UINavigationControllerDelegate协议或者, UIViewControllerTransitioningDelegate协议。根据需要的专场类型,实现自己的协议方法。

#pragma mark - pop / push
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    
    if (operation == UINavigationControllerOperationPush) {
        JTAnimatedTransition *animatedTransition = [JTAnimatedTransition animatedTransitionWithType:JTAnimatedTransitionTypePush];
        return animatedTransition;
    }
    return nil;
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (viewController != self) {
        self.selectImageView.frame = CGRectNull;
    }
}

#pragma mark - present / dismiss
-(id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [JTAnimatedTransition animatedTransitionWithType:JTAnimatedTransitionTypePresent];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [JTAnimatedTransition animatedTransitionWithType:JTAnimatedTransitionTypeDismiss];
}
首页push效果图.gif

3、模态跳转

模态跳转效果图.gif

调用跳转的代码

-(void)click:(UIButton *)sender
{
    ViewControllerThree *vc = [[ViewControllerThree alloc]init];
    
    [self presentViewController:vc animated:YES completion:^{
        
    }];
}

调用者 ViewController 内实现了协议方法

在返回时 在 ViewControllerThree 内需要遵循 UIViewControllerTransitioningDelegate 并实现其协议方法

#import "ViewControllerThree.h"
#import "JTAnimatedTransition.h"
@interface ViewControllerThree ()<UIViewControllerTransitioningDelegate>

@end

@implementation ViewControllerThree

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.transitioningDelegate = self;
    
    self.title = @"模态";
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    btn.backgroundColor = [UIColor redColor];
    [btn setTitle:@"点我返回" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
-(void)back
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [JTAnimatedTransition animatedTransitionWithType:JTAnimatedTransitionTypePresent];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [JTAnimatedTransition animatedTransitionWithType:JTAnimatedTransitionTypeDismiss];
}

@end

结束语

      写到这转场动画就自定义完成了。其实转场动画主要就是两个协议:1、在动画管理类内遵循UIViewControllerAnimatedTransitioning 2、在动画使用的类内遵循, UIViewControllerTransitioningDelegate以及UINavigationControllerDelegate协议,并实现其协议方法。
      如果你有什么更加炫酷的动画,只需要在JTAnimatedTransition内设置动画的位置写上自己想要的动画即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容