聯(lián)系人:石虎QQ: 1224614774? 昵稱:嗡嘛呢叭咪哄
@property(nonatomic,strong)UIButton *btnCountdown;//倒計時按鈕
//用 GCD實(shí)現(xiàn)倒計時功能
- (void)btnCountdownClick{
//倒計時默認(rèn)狀體
[_btnCountdown setTitle:@"重發(fā)(60s)" forState:UIControlStateNormal];
//倒計時時間
__block int timeout=59;
//倒計時全局隊(duì)列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//設(shè)置一個事件處理器
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//設(shè)置時間處理器時間
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結(jié)束,關(guān)閉
//取消事件處理器
dispatch_source_cancel(_timer);
//回到主線程
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
_btnCountdown.userInteractionEnabled = YES;
//設(shè)置倒計時標(biāo)題
[_btnCountdown setTitle:@"獲取驗(yàn)證碼" forState:UIControlStateNormal];
});
}else{
//去時間余
int seconds = timeout % 60;
//拿到時間文字
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
//回到主線程
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
[UIView beginAnimations:nil context:nil];
//設(shè)置動畫時間為1秒
[UIView setAnimationDuration:1];
//時間倒計時為0的時候顯示重發(fā)?秒
[_btnCountdown setTitle:[NSString stringWithFormat:@"重發(fā)(%@秒)",strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
_btnCountdown.userInteractionEnabled = NO;
});
timeout--;
}
});
dispatch_resume(_timer);
}