創(chuàng)建一個(gè)UIButton的類別蚊锹,其他控件也可以使用這個(gè)方法:
/*
* 倒計(jì)時(shí)按鈕
* @param timeLine 倒計(jì)時(shí)總時(shí)間
* @param title 還沒倒計(jì)時(shí)的title
* @param subTitle 倒計(jì)時(shí)的子名字 如:時(shí)、分
* @param mColor 還沒倒計(jì)時(shí)的顏色
* @param color 倒計(jì)時(shí)的顏色
*/
- (void)startWithTime:(NSInteger)timeLine
title:(NSString *)title
countDownTitle:(NSString *)subTitle
mainColor:(UIColor *)mColor
countColor:(UIColor *)color;
-(void)startWithTime:(NSInteger)timeLine
title:(NSString *)title
countDownTitle:(NSString *)subTitle
mainColor:(UIColor *)mColor
countColor:(UIColor *)color
{
//倒計(jì)時(shí)時(shí)間
__block NSInteger timeOut = timeLine;
//創(chuàng)建一個(gè)線程
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//創(chuàng)建一個(gè)時(shí)間源
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//時(shí)間每秒執(zhí)行一次
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
//小于0時(shí)
if (timeOut <= 0)
{
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
self.backgroundColor = mColor;
[self setTitle:title forState:UIControlStateNormal];
self.userInteractionEnabled = YES;
});
}
else
{
//大于0時(shí)計(jì)算需要顯示的文字
int seconds = (int)timeOut % 60;
NSString * timeStr = [NSString stringWithFormat:@"%0.2d",seconds];
dispatch_async(dispatch_get_main_queue(), ^{
self.backgroundColor = color;
[self setTitle:[NSString stringWithFormat:@"%@%@",timeStr,subTitle] forState:UIControlStateNormal];
self.userInteractionEnabled = NO;
});
timeOut--;
}
});
dispatch_resume(_timer);
}