iOS毫秒倒计时的实现

作者: 若锦 | 来源:发表于2017-01-11 15:43 被阅读837次

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

相关文章

  • iOS毫秒倒计时的实现

    app开发中,当展示限时优惠的某些商品时,往往会加一个倒计时,提示用户该商品限时优惠所剩的时间,。那对于开发者来说...

  • 倒计时

    ios怎么在cell上添加倒计时 iOS中 简单易懂的秒杀倒计时/倒计时 iOS开发-三种倒计时的写法 iOS实现...

  • js实现发送验证码的倒计时功能

    要求:实现一个验证码发送倒计时的功能 实现效果: 使用setInterval函数实现功能:按照指定的周期(以毫秒计...

  • iOS 毫秒倒计时列表

    近段的项目有个毫秒倒计时的需求,在网上找了好久,都没有找到明确的Demo或者毫秒倒计时的知识点,所以就借鉴了一些前...

  • 关于倒计时的几种

    Via From Net iOS倒计时的探究与选择 只用一个倒计时,改变数据源实现 一个倒计时,单例实现

  • GCD 实现倒计时功能

    其实iOS的倒计时实现思路有多种,个人感觉难点在在于如何实现后台倒计时,保证数据的准确性。所以我们在研究GCD实现...

  • 微信小程序实现活动倒计时

    1.实现效果 2.实现步骤 1.获取指定截止时间与当前时间的毫秒,即为剩余毫秒值,若剩余毫秒值小于0则返回0。 2...

  • 撸大湿iOS倒计时按钮SDK(在后台或切换页面依然倒计时)

    由于苹果官方对iOS系统后台任务管控非常严格,所以在iOS系统要实现倒计时进入后台或者切换页面之后依然能保持倒计时...

  • iOS实现倒计时的三种方式

    iOS实现倒计时的三种方式 做iOS app开发的过程当中,经常会出现获取验证码等需求,这个时候一般会使用倒计时来...

  • iOS快速实现一个保存记录的倒计时按钮

    iOS开发中在登录、注册、找回密码等页面经常需要实现倒计时按钮,但是很多情况下用户点击倒计时按钮开始倒计时之后,再...

网友评论

  • Zz7777777:cell 中用此性能消耗太大
    Zz7777777:@若锦 我这边用通知写的 cell 性能还算不错
    若锦:@PengJiang 嗯,我没有用在cell中的场景,对于在cell中,你这边有什么好的建议呀,分享分享:stuck_out_tongue_winking_eye::stuck_out_tongue_winking_eye:
  • 知之轩:好,之前面试问到过这个问题
    若锦:@知之轩 大神不敢当。推荐的话我还真的无能为力 :cold_sweat: ,你在哪里找的工作呢
    知之轩:@若锦 定时器用什么做,设备进入后台怎么处理,设备退出后台怎么开启?当然工作还没找到,求大神推荐
    若锦: 嗯,面试官问了啥内容呢,让我取取经吧:yum:
  • xiaomayi2012:f非常感谢正需要
  • Mg明明就是你:6
    若锦:@Mg明明就是你 好的好的,谢谢指出:stuck_out_tongue_winking_eye::stuck_out_tongue_winking_eye:已修改
    Mg明明就是你:@Mg明明就是你 最后暂停定时器的注释写反了
  • 9ea95b711416:不错,赞一个:+1:🏻

本文标题:iOS毫秒倒计时的实现

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