iOS毫秒倒计时的实现

app开发中,当展示限时优惠的某些商品时,往往会加一个倒计时,提示用户该商品限时优惠所剩的时间,。那对于开发者来说,这就需要我们去实现的是一个倒计时的功能,这个倒计时根据具体需求,可以以天、小时、分、秒、毫秒作单位。

今天呢,主要说说毫秒计时器。我们知道秒和毫秒之间的进制是1000,也就是说1秒=1000毫秒,那我们做毫秒倒计时器的时候是设置一个时间间隔为1毫秒的计时器,逐一减少毫秒数。但是这样的话太耗时了,所以很多的毫秒计时器中的毫秒数只是0-9之间的数字,这就意味着,这个毫秒计时器的时间间隔是100毫秒,这样相比起1毫秒为间隔的计时器,其消耗就少了很多,同时也达到毫秒计时的效果。

那对于整个毫秒倒计时的实现思路就是:得到未来某个日期的时间戳和当前日期的时间戳,计算这两者之间的时间差,然后设置一个时间间隔为100毫秒的计时器,每隔100毫秒,更新一下倒计时器上相应的数值。

自定义一个UIview,将倒计时封装起来。
一、在MsecCountDownView.h中增加时间戳和计时器这两属性

 
@interface MsecCountDownView : UIView
 
@property(nonatomic, assign)double timeInterval;//未来某个日期的时间戳
@property(nonatomic, strong)NSTimer *timer ; //定时器
 
@end

二、在MsecCountDownView.m实现相关UI及倒计时方法

@interface MsecCountDownView (){
UIView *countdownBackView;
CGFloat _passTime;
}
@property(nonatomic, strong)UILabel *tipLabel;
@property(nonatomic, strong)UILabel *hoursLabel;
@property(nonatomic, strong)UILabel *minutesLabel;
@property(nonatomic, strong)UILabel *secondsLabel;
@property(nonatomic, strong)UILabel *millionSecondsLabel;
@property(nonatomic, strong)UILabel *label1;
@property(nonatomic, strong)UILabel *label2;
@property(nonatomic, strong)UILabel *label3;
@property(nonatomic, strong)UILabel *label4;
@end

创建相关UI

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        
        countdownBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        [self addSubview:countdownBackView];
        _tipLabel=[[UILabel alloc] init];
        _tipLabel.frame = CGRectMake(0, 0, 40, countdownBackView.frame.size.height);
        [countdownBackView addSubview:_tipLabel];
     
        _tipLabel.font = [UIFont systemFontOfSize:12];
        
        
        //小时
        _hoursLabel=[[UILabel alloc] initWithFrame:CGRectMake(_tipLabel.frame.origin.x+_tipLabel.frame.size.width, 0, 35, countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_hoursLabel];
        _hoursLabel.font = [UIFont systemFontOfSize:11];
        
        _label1=[[UILabel alloc] initWithFrame:CGRectMake(_hoursLabel.frame.origin.x+_hoursLabel.frame.size.width, _hoursLabel.frame.origin.y, 8, countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_label1];
        
        //分钟
        _minutesLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label1.frame.origin.x+_label1.frame.size.width,  _hoursLabel.frame.origin.y, 20, countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_minutesLabel];
        _minutesLabel.font = [UIFont systemFontOfSize:11];
        
        _label2=[[UILabel alloc] initWithFrame:CGRectMake(_minutesLabel.frame.origin.x+_minutesLabel.frame.size.width,  _hoursLabel.frame.origin.y, 8, countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_label2];
        
      //秒
        _secondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label2.frame.origin.x+_label2.frame.size.width,  _hoursLabel.frame.origin.y, 20 , countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_secondsLabel];
 
        
        _secondsLabel.font = [UIFont systemFontOfSize:11];
        
        _label3=[[UILabel alloc] initWithFrame:CGRectMake(_secondsLabel.frame.origin.x+_secondsLabel.frame.size.width,  _hoursLabel.frame.origin.y, 8 , countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_label3];
        
        
        _millionSecondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label3.frame.origin.x+_label3.frame.size.width,  _hoursLabel.frame.origin.y, 20, countdownBackView.frame.size.height)];
        [countdownBackView addSubview:_millionSecondsLabel];
        
        
           //毫秒
        
        _millionSecondsLabel.font = [UIFont systemFontOfSize:11];
        
        _label1.textAlignment=1;
        _label2.textAlignment=1;
        _label3.textAlignment = 1;
        _hoursLabel.textAlignment=1;
        _minutesLabel.textAlignment=1;
        _secondsLabel.textAlignment=1;
        _millionSecondsLabel.textAlignment=1;
 
        
        _passTime=0.0;
    }
    
    
    return self;
}

生成一个计时器

//得到未来某个日期的时间戳,与当前时间戳相比,得到两者的时间差,生成定时器
- (void)setTimeInterval:(double)timeInterval
{
 
    _timeInterval = timeInterval ;
 
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
    dataFormatter.dateFormat = @"MM/dd/yyyy HH:mm:ss.SSS";
    
    //获取当前系统的时间,并用相应的格式转换
    [dataFormatter stringFromDate:[NSDate date]];
    NSString *currentDayStr = [dataFormatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [dataFormatter dateFromString:currentDayStr];
    
    //优惠结束的时间,也用相同的格式去转换
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000.0];
    NSString *deadlineStr = [dataFormatter stringFromDate:date];
    NSDate *deadlineDate = [dataFormatter dateFromString:deadlineStr];
    
    _timeInterval=[deadlineDate timeIntervalSinceDate:currentDate]*1000;
    
    if (_timeInterval!=0)
    {
        
        //时间间隔是100毫秒,也就是0.1秒
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
    }else{
        [countdownBackView removeFromSuperview];
        
    }
 
}

实现每隔100毫秒执行的方法,更新倒计时器上面相应的数值

 
// 每间隔100毫秒定时器触发执行该方法
- (void)timerAction
{
   
    [self getTimeFromTimeInterval:_timeInterval] ;
    
   
    // 当时间间隔为0时干掉定时器
    if (_timeInterval-_passTime == 0)
    {
        [_timer invalidate] ;
        _timer = nil ;
    }
}

// 通过时间间隔计算具体时间(小时,分,秒,毫秒)
- (void)getTimeFromTimeInterval : (double)timeInterval
{

    //1s=1000毫秒
    _passTime += 100.f;//毫秒数从0-9,所以每次过去100毫秒
    _tipLabel.text=@"还剩:";
 
    _label3.text=@".";
    _label2.text=@":";
    _label1.text=@":";
    
    //小时数
    NSString *hours = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60/60)];
    //分钟数
    NSString *minute = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60)%60];
    //秒数
    NSString *second = [NSString stringWithFormat:@"%ld", ((NSInteger)(timeInterval-_passTime))/1000%60];
    //毫秒数
    CGFloat sss = ((NSInteger)((timeInterval - _passTime)))%1000/100;
    
    
    NSString *ss = [NSString stringWithFormat:@"%.lf", sss];
    
    if (minute.integerValue < 10) {
        minute = [NSString stringWithFormat:@"0%@", minute];
    }
    
 
    self.hoursLabel.text = [NSString stringWithFormat:@"%@",hours];
    self.minutesLabel.text = [NSString stringWithFormat:@"%@",minute];
    self.secondsLabel.text = [NSString stringWithFormat:@"%@",second];
    self.millionSecondsLabel.text = [NSString stringWithFormat:@"%@",ss];
    
    if (timeInterval - _passTime <= 0) {
        [countdownBackView removeFromSuperview];
        [self removeFromSuperview];
    }
    
}

三、在ViewController.m给倒计时器赋值,实现自己想要的倒计时

 

- (void)viewDidLoad {
    [super viewDidLoad];
 
    msecView=[[MsecCountDownView alloc] initWithFrame:CGRectMake(50, 100, self.view.frame.size.width-100, 16)];
    [self.view addSubview:msecView];
 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
 
 
    NSDate* date = [formatter dateFromString:@"2017-04-11 15:10:00.000"];
    //将日期转换成时间戳
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue]*1000;
  
    msecView.timeInterval=timeSp;
 
}

这样就实现倒计时的功能了。但是使用倒计时还需要注意一点,当离开该页面的时候,记得把定时器暂停,等回到该页面的时候再启动倒计时。 这个可以通过以下两方法实现。

 
-(void)viewWillAppear:(BOOL)animated{
 
//    页面出现时,开启计时器 
    [msecView.timer setFireDate:[NSDate distantPast]];
    
}
-(void)viewWillDisappear:(BOOL)animated{
//    页面消失时,暂停提示器
    [msecView.timer setFireDate:[NSDate distantFuture]];
}
如有需要,可点击demo到GitHub上下载

demo

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,087评论 18 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,477评论 6 13
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • ----------------------- 页面 1----------------------- 2013 ...
    长春傳齐3阅读 4,060评论 0 1
  • 2倍图3倍图的用法之前一直用的很混乱,自己写了个例子来验证了一下,现在写出来吧。UIImage的加载有两种方法 1...
    iCuiCui阅读 1,085评论 0 3