一.之前電商項(xiàng)目做過(guò)的倒計(jì)時(shí)功能戒傻,筆記一下友瘤。
主要有兩種思路:①:根據(jù)當(dāng)前系統(tǒng)時(shí)間和搶購(gòu)結(jié)束時(shí)間計(jì)算差值挤土,計(jì)算倒計(jì)時(shí)识虚。 ②:后臺(tái)返回當(dāng)前時(shí)間距離搶購(gòu)結(jié)束時(shí)間的總秒數(shù)肢扯。根據(jù)秒數(shù)本地倒計(jì)時(shí)。(第二種方案更為準(zhǔn)確担锤,不受本地時(shí)間誤差的影響)
代碼如下:
方案一:根據(jù)當(dāng)前系統(tǒng)時(shí)間和搶購(gòu)結(jié)束時(shí)間計(jì)算差值蔚晨,計(jì)算倒計(jì)時(shí)。在cell的m文件中計(jì)算肛循。但是系統(tǒng)時(shí)間可能有誤差铭腕,導(dǎo)致計(jì)時(shí)準(zhǔn)確性有待提高银择。
1.cell的.h文件中定義屬性字段@property(nonatomic,copy) NSString* endTime;
2:cell的.m文件中重寫(xiě)endTime的set方法,傳入結(jié)束日期累舷。
- (void)setEndTime:(NSString *)endTime
{
_endTime =endTime;
NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshTime:) userInfo:nil repeats:YES];
[self refreshTime:time];
[[NSRunLoop currentRunLoop] addTimer:time forMode:NSRunLoopCommonModes];
}
- (void)refreshTime:(NSTimer *)tm
{
NSDate *currentDate =[NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSDayCalendarUnit | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *commponent = [calendar components:unit fromDate:currentDate toDate:[HFTools getDateWithString:_endTime ] options:NSCalendarWrapComponents];
NSDate *dt = [[HFTools getDateWithString:_endTime] earlierDate:currentDate];
if([dt isEqualToDate:[HFTools getDateWithString:_endTime ]])
{
[tm invalidate];
self.daoJiShiLabel.text = [NSString stringWithFormat:@"剩余0天 已結(jié)束"];
}else
{
self.daoJiShiLabel.text = [NSString stringWithFormat:@"剩余%zd天 %02zd:%02zd:%02zd",commponent.day,commponent.hour,commponent.minute,commponent.second];
}
}
/******************
//其中[HFTools getDateWithString:_endTime ]方法為:
+(NSDate*)getDateWithString:(NSString *)time{
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//實(shí)例化一個(gè)NSDateFormatter對(duì)象
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
NSDate *date =[dateFormat dateFromString:time];
return date;
}
方案二:
**方案二:后臺(tái)給出距離搶購(gòu)結(jié)束的總秒數(shù)浩考,根據(jù)總秒數(shù),計(jì)算倒計(jì)時(shí)被盈。(計(jì)時(shí)準(zhǔn)確.)怀挠。
![countDownPic.gif](http://upload-images.jianshu.io/upload_images/1486049-1d675936523b06f0.gif?imageMogr2/auto-orient/strip)
代碼:
#pragma mark - - 倒計(jì)時(shí)Timer..
- (void)initCountDown {
for (NSInteger i = 0; i < self.dataArray.count; i++)
{
//將倒計(jì)時(shí)總秒數(shù)數(shù)組根據(jù)indexpath依次存入字典
NSDictionary *CountDic = @{@"indexPath":[NSString stringWithFormat:@"%ld",i],@"lastTime": self.dataArray[i]};
[self.countDownDataArray addObject:CountDic];
}
// 防止刷新界面的時(shí)候創(chuàng)建多個(gè)定時(shí)器,導(dǎo)致多個(gè)定時(shí)器一起倒計(jì)時(shí)害捕。
if (!self.MainTimer) {
[self startTimer];
}
}
//倒計(jì)時(shí)
- (void)startTimer
{
self.MainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
//如果不添加下面這條語(yǔ)句绿淋,在UITableView拖動(dòng)的時(shí)候,會(huì)阻塞定時(shí)器的調(diào)用
[[NSRunLoop currentRunLoop] addTimer:self.MainTimer forMode:UITrackingRunLoopMode];
}
//刷新時(shí)間
- (void)refreshLessTime
{
NSUInteger time;
for (int i = 0; i < self.countDownDataArray.count; i++) {
time = [[[self.countDownDataArray objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[[[self.countDownDataArray objectAtIndex:i] objectForKey:@"indexPath"] integerValue] inSection:0];
NSInteger oldTime;
if (time == 0) {
oldTime = 0;
}else {
oldTime = --time;
}
NSString *str;
str = [NSString stringWithFormat:@"%@",[self lessSecondToDay:oldTime]];
//根據(jù)indexpath取cell
YMCountDownCell *cell = (YMCountDownCell *)[self.tableView cellForRowAtIndexPath:indexPath];
cell.countDownLabel.text = [self lessSecondToDay:oldTime];
//將倒計(jì)時(shí)后的秒數(shù)存入數(shù)組尝盼,刷新數(shù)據(jù)源吞滞。
NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%ld",indexPath.row],@"lastTime": [NSString stringWithFormat:@"%ld",time]};
[self.countDownDataArray replaceObjectAtIndex:i withObject:dic];
}
}
//根據(jù)秒數(shù)計(jì)算剩余時(shí)間:天,小時(shí)盾沫,分鐘裁赠,秒
- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
NSUInteger day = (NSUInteger)seconds/(24*3600);
NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
NSUInteger min = (NSUInteger)(seconds%(3600))/60;
NSUInteger second = (NSUInteger)(seconds%60);
NSString *timeStr;
if (seconds == 0) {
timeStr = @"已結(jié)束";
[self countDownFinished];
}else {
timeStr = [NSString stringWithFormat:@"%02zd天 %02zd:%02zd:%02zd",(unsigned long)day,(unsigned long)hour,(unsigned long)min,(unsigned long)second];
}
return timeStr;
}
// do something when the The countdown ends
- (void)countDownFinished
{
}
注意:倒計(jì)時(shí)開(kāi)始會(huì)有一秒的刷新空檔期,可以鋪上倒計(jì)時(shí)數(shù)據(jù)防止倒計(jì)時(shí)UI一片白.(如果有刷新赴精,刷新的時(shí)候要更新數(shù)據(jù)源 self.dataArray)佩捞。
我用的tableview,所以就在cell上鋪蕾哟。
NSInteger backTime = [self.dataArray[indexPath.row] integerValue];
NSString *backStr = [self lessSecondToDay:backTime];
cell.countDownLabel.text = backStr;
最后附上方案二的github鏈接 倒計(jì)時(shí)Demo
ps:如果有好的思路歡迎拍磚交流哈一忱。