iOS 仿直播321倒计时动画

一、前言

今天碰到一个需求,仿全民直播的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
实现一个功能有很多种方法,我这个方法怎么样呢,感觉对你有帮助的话给个赞吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值