美文网首页swift3.0iOS Developerswift
iOS 仿直播321倒计时动画

iOS 仿直播321倒计时动画

作者: calary | 来源:发表于2017-07-25 23:09 被阅读388次

    一、前言

    今天碰到一个需求,仿全民直播的321倒计时动画,类似下图的效果,其实仔细想想并不难,但在网上找了下,有的做的还是有点复杂了,在这里分享下我的做法。


    未命名.gif

    二、分析

    无非就是一个倒计时,这里NSTimer实现,然后一个Label,并且对Label里的数字实施动画,产生如图的效果。这里动画采用的是CAKeyframeAnimation,因为它可以设置变化数组,符合我们的放大缩小复原需求。

    三、代码

    这里自定义了个CountdownLabel继承制UILabel,并在内部实现了倒计时,默认开始时间是3。

    //.h文件
    #import <UIKit/UIKit.h>
    
    @interface CountdownLabel : UILabel
    //开始倒计时时间
    @property (nonatomic, assign) int count;
    
    //执行这个方法开始倒计时
    - (void)startCount;
    @end
    
    
    //.m文件
    #import "CountdownLabel.h"
    
    @interface CountdownLabel()
    @property (nonatomic, strong) NSTimer *timer;
    
    @end
    
    @implementation CountdownLabel
    
    //开始倒计时
    - (void)startCount{
        [self initTimer];
    }
    
    - (void)initTimer{
        //如果没有设置,则默认为3
        if (self.count == 0){
            self.count = 3;
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    
    - (void)countDown{
        if (_count > 0){
            self.text = [NSString stringWithFormat:@"%d",_count];
            CAKeyframeAnimation *anima2 = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
          //字体变化大小
            NSValue *value1 = [NSNumber numberWithFloat:3.0f];
            NSValue *value2 = [NSNumber numberWithFloat:2.0f];
            NSValue *value3 = [NSNumber numberWithFloat:0.7f];
            NSValue *value4 = [NSNumber numberWithFloat:1.0f];
            anima2.values = @[value1,value2,value3,value4];
            anima2.duration = 0.5;
            [self.layer addAnimation:anima2 forKey:@"scalsTime"];
            _count -= 1;
        }else {
            [_timer invalidate];
            [self removeFromSuperview];
        }
    }
    

    具体用法

    #import "CountdownLabel.h"
    ...
    ...
    //倒计时动画
    - (void)initCountdownLabel{
        CountdownLabel *countdownLabel = [[CountdownLabel alloc] initWithFrame:CGRectMake(0, 350, 100, 30)];
        countdownLabel.textAlignment = NSTextAlignmentCenter;
        countdownLabel.textColor = [UIColor whiteColor];
        countdownLabel.font =  [UIFont systemFontOfSize:25];
        [self.view addSubview:countdownLabel];
        
        //可以在合适的地方 -开始倒计时
        [countdownLabel startCount];
    }
    
    

    四、总结

    代码已上传GitHub
    如果你想直接使用,就下载代码,将HHCountdownLabel直接拖入项目使用吧,label的初始化都是一样的,只是在显示的地方调用方法startCount就可以了。
    实现一个功能有很多种方法,我这个方法怎么样呢,感觉对你有帮助的话给个赞吧。

    相关文章

      网友评论

        本文标题:iOS 仿直播321倒计时动画

        本文链接:https://www.haomeiwen.com/subject/agggkxtx.html