今天要做类似拼多多那样额倒计时,并进行广告式轮播滚动。先奉上部分代码,具体demo稍后发布到github上。希望对大家能够有所帮助
- (void)timerStop {
if (_timer) {
[_timer invalidate];
_timer = nil;
}
}
- (void)timerStart {
if (!_timer && _remainTime > 0) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(countdownAction) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
}
}
- (void)countdownAction {
if (_remainTime <= 0) {
[self timerStop];
} else {
_remainTime -= 100;
NSString *days = [NSString stringWithFormat:@"%ld", (NSInteger)((_remainTime)/1000)/(3600*24)];
//小时数
NSString *hour = [NSString stringWithFormat:@"%ld", (NSInteger)((_remainTime)/1000)/60/60%24];
//分钟数
NSString *minute = [NSString stringWithFormat:@"%ld", (NSInteger)((_remainTime)/1000)/60%60];
//秒数
NSString *second = [NSString stringWithFormat:@"%ld", ((NSInteger)(_remainTime)/1000)%60];
CGFloat sss = _remainTime%1000/100;
NSString *ss = [NSString stringWithFormat:@"%.lf", sss];
if (hour.integerValue && hour.integerValue < 10) {
hour = [NSString stringWithFormat:@"0%@", hour];
}
if (minute.integerValue < 10) {
minute = [NSString stringWithFormat:@"0%@", minute];
}
if (second.integerValue < 10) {
second = [NSString stringWithFormat:@"0%@", second];
}
if (ss.integerValue < 10) {
ss = [NSString stringWithFormat:@"0%@", ss];
}
if (days.integerValue) {
self.joinDayLabel.text = [NSString stringWithFormat:@"剩余%@天%@:%@:%@", days ,hour, minute, second];
self.joinSSSLabel.text = [NSString stringWithFormat:@":%@",ss];
} else {
if (hour.integerValue) {
self.joinDayLabel.text = [NSString stringWithFormat:@"剩余%@:%@:%@",hour, minute, second];
self.joinSSSLabel.text = [NSString stringWithFormat:@":%@",ss];
}else{
self.joinDayLabel.text = [NSString stringWithFormat:@"剩余%@:%@", minute, second];
self.joinSSSLabel.text = [NSString stringWithFormat:@":%@",ss];
}
}
}
}
//时间差计算
- (double)computeDaysWithDataFromString:(NSString *)string{
//首先创建格式化对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
//然后创建日期对象
NSDate *date1 = [dateFormatter dateFromString:string];
NSDate *date = [NSDate date];
//计算时间间隔(单位是秒)
NSTimeInterval time = [date1 timeIntervalSinceDate:date];
return round(time*1000);
}