你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS發送驗證碼倒計時應用

iOS發送驗證碼倒計時應用

編輯:IOS開發綜合

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


具體代碼實現如下:

- (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); //每秒執行 
 dispatch_source_set_event_handler(_timer, ^{ //每秒鐘回調的方法 跟NSTimer 一樣的的執行方法 
  if(timeout<=0){ //倒計時結束,關閉 
   dispatch_source_cancel(_timer); 
    
   dispatch_async(dispatch_get_main_queue(), ^{ 
    //設置界面的按鈕顯示 
    [sender setTitle:@"發送驗證碼" 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]); 
    //設置界面的按鈕顯示 
    [sender setTitle:[NSString stringWithFormat:@"(%@)重新獲取",strTime] forState:UIControlStateDisabled]; 
    sender.enabled = NO; 
   }); 
   timeout--; 
  } 
 }); 
 //一定要調用resume 開啟定時器的功能 
} 

這個button可以直接在storyboard中實現,button的背景顏色選為灰色,再設置一個背景圖片,如上圖的紅色圖片,button的type設置為:custom

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved