倒计时效果

倒计时效果
文章图片
CountDown.png

// 全局 { dispatch_source_t_timer; }

#pragma mark 倒计时 - (void)countdownFromTimeString:(NSString *)timeString { if (!_timer) { // 倒计时时间 __block int timeout = timeString?[timeString intValue]:0; 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(_timer); _timer = nil; dispatch_async(dispatch_get_main_queue(), ^{ _dayLabel.text = @"00"; _hourLabel.text = @"00"; _minuteLabel.text = @"00"; _secondLabel.text = @"00"; }); }else{ int days = (int)(timeout/(3600*24)); if (days==0) { _dayLabel.text = @"00"; } int hours = (int)((timeout-days*24*3600)/3600); int minute = (int)(timeout-days*24*3600-hours*3600)/60; int second = timeout-days*24*3600-hours*3600-minute*60; dispatch_async(dispatch_get_main_queue(), ^{ _dayLabel.text = [NSString stringWithFormat:@"%0*d",2, days]; _hourLabel.text = [NSString stringWithFormat:@"%02d", hours]; _minuteLabel.text = [NSString stringWithFormat:@"%02d", minute]; _secondLabel.text = [NSString stringWithFormat:@"%02d", second]; }); timeout--; } }); dispatch_resume(_timer); } } }

    推荐阅读