如果有帮助到你就给个赞吧 谢谢咯...
添加到 单利类 或者button分类理都可以
返回之后再重新进来按钮倒计时会重置 不会在后台继续
/**
* 倒计时按钮
*
* @param timeLine 倒计时总时间
* @param title 还没倒计时的title 结束时的
* @param subTitle 倒计时中的子名字,如时、分
* @param mColor 还没倒计时的颜色
* @param color 倒计时中的颜色
* @param button 要操作的按钮
*/
- (void)startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color disposeButton:(UIButton *)button{
//倒计时时间
__block NSInteger timeOut = timeLine;
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_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
//倒计时结束,关闭
if (timeOut <= 0) {
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
button.backgroundColor = mColor;
[button setTitle:title forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
});
} else {
int allTime = (int)timeLine + 1;
int seconds = timeOut % allTime;
NSString *timeStr = [NSString stringWithFormat:@"%0.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
button.backgroundColor = color;
[button setTitle:[NSString stringWithFormat:@"%@%@",timeStr,subTitle] forState:UIControlStateNormal];
button.userInteractionEnabled = NO;
});
timeOut--;
}
});
dispatch_resume(_timer);
}
#pragma mark - 倒计时按钮 跳转页面不重置时间 (返回的话还会重置)
+ (void)startSeniorWithTime:(NSInteger)timeLine
title:(NSString *)title
countDownTitle:(NSString *)subTitle
mainColor:(UIColor *)mColor
countColor:(UIColor *)color
disposeButton:(UIButton *)button {
int __block time = (int) timeLine;
button.enabled = NO;
//获取系统全局队列
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);
//设置定时器为点击后马上开始,间隔时间为1秒,没有延迟
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), 1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
if (time == 0) {
button.enabled = YES;
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
button.backgroundColor = mColor;
[button setTitle:title forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
});
} else {
time--;
NSString *string = [NSString stringWithFormat:@"%d%@", time, subTitle];
dispatch_async(dispatch_get_main_queue(), ^{
button.backgroundColor = color;
[button setTitle:[NSString stringWithFormat:@"%@", string] forState:UIControlStateNormal];
button.userInteractionEnabled = NO;
});
}
});
dispatch_resume(timer);
}
干货代码 我的一个纯代码的基础框架有各种常用的分类封装入手即用