1 获取当前时间 和目标时间 计算相差多少
2 使用gcd 获取倒计时
3 属性字符串 设置 时分秒 的字体和背景色
{
dispatch_source_t _timer;
}
NSString *deadlineStr = self.model.auction.endTime;
NSString *nowStr = [NSString getCurrentTimeyyyymmdd];
NSInteger secondsCountDown = [NSString getDateDifferenceWithNowDateStr:nowStr deadlineStr:deadlineStr];
[self setdata:secondsCountDown];
- (void)setdata:(NSInteger)secondsCountDown{
__weak __typeof(self) weakSelf = self;
if (_timer == nil) {
__block NSInteger timeout = secondsCountDown; // 倒计时时间
if (timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(timeout <= 0){ // 当倒计时结束时做需要的操作: 关闭 活动到期不能提交
dispatch_source_cancel(self->_timer);
self->_timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
// weakSelf.timeLabel.text = @"当前活动已结束";
weakSelf.headerView.titleLabel.text = @"已结束";
});
} else { // 倒计时重新计算 时/分/秒
NSInteger days = (int)(timeout/(3600*24));
NSInteger hours = (int)((timeout-days*24*3600)/3600);
NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
NSString *strTime = [NSString stringWithFormat:@"距结束还有: %02ld 时 %02ld 分 %02ld 秒",hours, minute,second];
dispatch_async(dispatch_get_main_queue(), ^{
if (days == 0) {
// weakSelf.headerView.titleLabel.text = strTime;
NSString *endstr = strTime;
NSMutableAttributedString *mutablestr = [[NSMutableAttributedString alloc]initWithString:endstr];
NSDictionary *attris = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSBackgroundColorAttributeName: ZHColor(140, 190, 250, 1),NSForegroundColorAttributeName:[UIColor whiteColor]};
[mutablestr setAttributes:attris range:NSMakeRange(7,2)];
[mutablestr setAttributes:attris range:NSMakeRange(12,2)];
[mutablestr setAttributes:attris range:NSMakeRange(17,2)];
weakSelf.headerView.titleLabel.attributedText = mutablestr;
} else {
NSString *endstr = [NSString stringWithFormat:@"距结束还有: %ld 天 %02ld 时 %02ld 分 ",days,hours, minute];
NSMutableAttributedString *mutablestr = [[NSMutableAttributedString alloc]initWithString:endstr];
NSDictionary *attris = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSBackgroundColorAttributeName: ZHColor(140, 190, 250, 1),NSForegroundColorAttributeName:[UIColor whiteColor]};
[mutablestr setAttributes:attris range:NSMakeRange(7,2)];
[mutablestr setAttributes:attris range:NSMakeRange(12,2)];
[mutablestr setAttributes:attris range:NSMakeRange(17,2)];
weakSelf.headerView.titleLabel.attributedText = mutablestr;
}
});
timeout--; // 递减 倒计时-1(总时间以秒来计算)
}
});
dispatch_resume(_timer);
}
}
}