app注冊的時候,經(jīng)常會遇到發(fā)送驗證碼的功能,當(dāng)點擊發(fā)送驗證碼的時候,那個button就開始了倒計時,當(dāng)計時結(jié)束才可以重新發(fā)送,效果如下:

具體代碼實現(xiàn)如下:
- (IBAction)sendMes:(UIButton *)sender { __block int timeout = 10 ; //倒計時時間 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, ^{ //每秒鐘回調(diào)的方法 跟NSTimer 一樣的的執(zhí)行方法 if(timeout<=0){ //倒計時結(jié)束,關(guān)閉 dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{ //設(shè)置界面的按鈕顯示 [sender setTitle:@"發(fā)送驗證碼" forState:UIControlStateNormal]; sender.enabled = YES; }); }else{ int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d", seconds]; dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"----%@", [NSThread currentThread]); //設(shè)置界面的按鈕顯示 [sender setTitle:[NSString stringWithFormat:@"(%@)重新獲取",strTime] forState:UIControlStateDisabled]; sender.enabled = NO; }); timeout--; } }); //一定要調(diào)用resume 開啟定時器的功能 } 這個button可以直接在storyboard中實現(xiàn),button的背景顏色選為灰色,再設(shè)置一個背景圖片,如上圖的紅色圖片,button的type設(shè)置為:custom
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選