/*
1、继承自UILabel,基本用法与UILabel相同,在UILabel的基础上添加了倒计时功能
2、时间格式为(分:秒)均显示两位数字,00:00
3、调用- (void)startCountdown:(NSTimeInterval)timeCount方法,设置倒计时总秒数,开始倒计时
4、通过属性timeOutBlock,获得倒计时结束的回调
*/
@interface CountdownTimerLabel : UILabel
/*
倒计时结束回调
*/
@property(nonatomic, copy) dispatch_block_t timeOutBlock;
/*
开始倒计时
*/
- (void)startCountdown:(NSTimeInterval)timeCount;
@end
@interface CountdownTimerLabel() {
dispatch_source_t timer;
NSInteger timeRemaining;
}
@end
@implementation CountdownTimerLabel
- (void)startCountdown:(NSTimeInterval)timeCount {
[self showCountdown];
__weaktypeof(self) weakSelf =self;
timeRemaining= timeCount;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_TARGET_QUEUE_DEFAULT, 0);
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if(self->timeRemaining<=0) {
dispatch_source_cancel(self->timer);
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf timeOut];
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
self->timeRemaining--;
[weakSelf showCountdown];
});
}
});
dispatch_resume(timer);
}
- (void)showCountdown {
NSInteger minutes =floor(timeRemaining/60);
NSInteger seconds =trunc(timeRemaining- minutes *60);
self.text= [NSString stringWithFormat:@"%02ld:%02ld",minutes,seconds];
}
- (void)timeOut {
if (_timeOutBlock) {
_timeOutBlock();
}
}
- (void)dealloc {
if(timer) {
dispatch_source_cancel(timer);
timer=nil;
}
}