//// CountdownButton.h// Standardization//// Created by YuFly on 2017/10/16.// Copyright © 2017年 strong. All rights reserved.//#import@class CountdownButton;typedef void(^Completion)(CountdownButton *countdownButton);@interface CountdownButton : UIButton/** 倒计时 @param startTime 倒计时时间 @param timeUnit 时间单位 @param completion 结束回调 */- (void)countDownButtonWithStartTime:(NSInteger)startTime timeUnit:(NSString *)timeUnit endTitle:(NSString *)endTitle completion:(Completion)completion;@end
//// CountdownButton.m// Standardization//// Created by YuFly on 2017/10/16.// Copyright © 2017年 strong. All rights reserved.//#import "CountdownButton.h"@implementation CountdownButton- (void)countDownButtonWithStartTime:(NSInteger)startTime timeUnit:(NSString *)timeUnit endTitle:(NSString *)endTitle completion:(Completion)completion{ __unsafe_unretained CountdownButton *ws=self; NSInteger beginTime = startTime; if([[timeUnit lowercaseString] isEqualToString:@"s"]) beginTime = startTime; else if([[timeUnit lowercaseString] isEqualToString:@"min"]) beginTime = startTime*60; else if([[timeUnit lowercaseString] isEqualToString:@"h"]) beginTime = startTime*60*60; __block NSInteger remainTime = beginTime; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{ if (remainTime <= 0) { // 倒计时结束 dispatch_source_cancel(timer); dispatch_async(dispatch_get_main_queue(), ^{ [ws setTitle:[NSString stringWithFormat:@"%@",endTitle] forState:UIControlStateDisabled]; ws.enabled = YES; completion(ws); }); } else { NSString *timeStr = [ws getMMSSFromSS:[NSString stringWithFormat:@"%ld", remainTime] timeUnit:timeUnit]; dispatch_async(dispatch_get_main_queue(), ^{ [ws setTitle:[NSString stringWithFormat:@"允许%@倒计时%@",endTitle,timeStr] forState:UIControlStateDisabled]; ws.enabled = NO; }); remainTime--; } }); dispatch_resume(timer);}-(NSString *)getMMSSFromSS:(NSString *)timeString timeUnit:(NSString *)timeUnit{ NSInteger seconds = [timeString integerValue]; NSString *hour = [NSString stringWithFormat:@"%02ld",seconds/3600]; NSString *minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60]; NSString *second = [NSString stringWithFormat:@"%02ld",seconds%60]; NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",hour,minute,second]; if([[timeUnit lowercaseString] isEqualToString:@"s"]) { format_time= timeUnit; } else if([[timeUnit lowercaseString] isEqualToString:@"min"]) { format_time = [NSString stringWithFormat:@"%@:%@",minute,second]; } return format_time;}@end