@property (nonatomic,strong) dispatch_source_t timer;
// startTime 为时间戳
[self downSecondHandle:startTime ];
-(void)downSecondHandle:(NSString*)aTimeString
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate*endDate = [dateFormatterdateFromString:[selftimeWithTimeIntervalString:aTimeString]];//结束时间
NSDate *endDate_tomorrow = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:([endDate timeIntervalSinceReferenceDate])];
NSDate*startDate = [NSDatedate];
NSTimeIntervaltimeInterval =[endDate_tomorrowtimeIntervalSinceDate:startDate];
//得到的是 开始时间 与现在时间的间隔 时间 也就是倒计时的时间
if(_timer==nil)
{
__blockinttimeout = timeInterval;//倒计时时间 ()
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)
{
//倒计时结束,关闭 //倒计时结束之后改变文字为 距离结束1小时倒计时
dispatch_source_cancel(_timer);
_timer=nil;
dispatch_async(dispatch_get_main_queue(), ^{
self.hourLabel.text=@"00";
self.minutesLabel.text=@"00";
self.secondsLabel.text=@"00";
});
}
else
{
// int days = (int)(timeout/(3600*24));
inthours = (int)(timeout/3600);
intminute = (int)(timeout-hours*3600)/60;
intsecond = timeout-hours*3600-minute*60;
dispatch_async(dispatch_get_main_queue(), ^{
if(hours<10)
{
self.hourLabel.text= [NSStringstringWithFormat:@"0%d",hours];
}
else
{
self.hourLabel.text= [NSStringstringWithFormat:@"%d",hours];
}
if(minute<10)
{
self.minutesLabel.text= [NSStringstringWithFormat:@"0%d",minute];
}
else
{
self.minutesLabel.text= [NSStringstringWithFormat:@"%d",minute];
}
if(second<10)
{
self.secondsLabel.text= [NSStringstringWithFormat:@"0%d",second];
}
else
{
self.secondsLabel.text= [NSStringstringWithFormat:@"%d",second];
}
});
timeout--;
}
});
dispatch_resume(_timer);
}
}
}
暂时没有解决collectionview cell重用会导致倒计时与商品不匹配! 此方法暂时只在创建一次的时候使用