iOS GCD實現(xiàn)獲取驗證碼的倒計時

聯(lián)系人:石虎QQ: 1224614774? 昵稱:嗡嘛呢叭咪哄

@property(nonatomic,strong)UIButton *btnCountdown;//倒計時按鈕

//用 GCD實現(xiàn)倒計時功能

- (void)btnCountdownClick{

//倒計時默認狀體

[_btnCountdown setTitle:@"重發(fā)(60s)" forState:UIControlStateNormal];

//倒計時時間

__block int timeout=59;

//倒計時全局隊列

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); //每秒執(zhí)行

dispatch_source_set_event_handler(_timer, ^{

if(timeout<=0){ //倒計時結(jié)束,關(guān)閉

//取消事件處理器

dispatch_source_cancel(_timer);

//回到主線程

dispatch_async(dispatch_get_main_queue(), ^{

//設置界面的按鈕顯示 根據(jù)自己需求設置

_btnCountdown.userInteractionEnabled = YES;

//設置倒計時標題

[_btnCountdown setTitle:@"獲取驗證碼" forState:UIControlStateNormal];

});

}else{

//去時間余

int seconds = timeout % 60;

//拿到時間文字

NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

//回到主線程

dispatch_async(dispatch_get_main_queue(), ^{

//設置界面的按鈕顯示 根據(jù)自己需求設置

[UIView beginAnimations:nil context:nil];

//設置動畫時間為1秒

[UIView setAnimationDuration:1];

//時間倒計時為0的時候顯示重發(fā)?秒

[_btnCountdown setTitle:[NSString stringWithFormat:@"重發(fā)(%@秒)",strTime] forState:UIControlStateNormal];

[UIView commitAnimations];

_btnCountdown.userInteractionEnabled = NO;

});

timeout--;

}

});

dispatch_resume(_timer);

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容