iOS中倒计时实现效果

来源:互联网 发布:飞利浦x830软件 编辑:程序博客网 时间:2024/05/31 15:19

很多商城类的APP中都有活动,过活动给的话都会有期限的,目前我就遇到了这样的事情。
下面是后台数据
这里写图片描述
明显的这是格林尼治时间,然后求出与当前时间的时间差,展示出来。用一个计时器去按规定的时间调用计算时间差的方法就可以了。
效果如下
这里写图片描述

在此关于展示我用的是label,这里就不在多说,只介绍计算时间差、启动计时器,关闭计时器等。

1、获取数据。我这里是在定制的cell里面,因为还有其他数据,所以比较繁琐了点,根据需要设置。再此就不在刻意简化了

-(void)infoData:(NSArray *)array success:(flashSalesBlock)block{    for (NSDictionary * dic in array) {        AdIDModel * idModel = [[AdIDModel alloc] initWithDictionary:dic error:nil];        if (idModel._id == 82) {            for (NSDictionary *dic in idModel.ad) {                NewAdModel * Model = [[NewAdModel alloc] initWithDictionary:dic error:nil];                [_modelArray addObject:Model];            }        }    }    [self addData];    [self timeData];    if (_modelArray.count>1) {        NewAdModel * model = _modelArray[0];        if ([model.ad_code isEqualToString:@""]) {                block(NO);        }else{            block(YES);        }    }}

2、取出活动结束时间,启动计时器

-(void)timeData{    if (_modelArray.count>0) {        NewAdModel * model = _modelArray[0];        NSString * timeStr = model.endTime;        _timeString = timeStr;        //启动计时器,进行倒计时           _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeBegin) userInfo:nil repeats:YES];    }}

3、计时器调用的方法,获取时差。并根据时差判断活动是否结束,停止计时器

-(void)timeBegin{    NSString * timeStr = [self compareCurrentTime:_timeString];//活动结束,停止计时器,显示活动结束。    if ([timeStr isEqualToString:@"00 00 00"]) {        _overLabel.alpha = 1;        [_timer invalidate];        _timer = nil;    }}

4、计算时差的方法,我这里是时分秒是分开展示的。

//剩余时间- (NSString *)compareCurrentTime:(NSString *)currentTime{    NSInteger time = [currentTime integerValue];    NSDate *currentDate = [NSDate dateWithTimeIntervalSince1970:time];    NSTimeInterval timeInterval = [currentDate timeIntervalSinceNow];    NSInteger second = (NSInteger)timeInterval;    NSString *str_second = [NSString stringWithFormat:@"%02d", second%60];    NSString *str_minute = [NSString stringWithFormat:@"%02d", second/60%60];    NSString *str_hour = [NSString stringWithFormat:@"%02d", second/60/60];    NSString * remainingTimeStr = [NSString stringWithFormat:@"%@ %@ %@", str_hour, str_minute, str_second];    _timeLabel3.text = str_second;    _timeLabel2.text = str_minute;    _timeLabel1.text = str_hour;    return remainingTimeStr;}
0 0
原创粉丝点击