iOS實現短信驗證碼倒計時

這篇文章主要介紹了iOS實現短信驗證碼倒計時功能,一種方法是利用NSTimer計時器,另一種方法是利用GCD實現短信驗證碼倒計時,具有一定的參考價值,感興趣的小夥伴們可以參考一下

在開發中,經常在需要用戶註冊的時候會需要實現驗證碼倒計時的功能,下面是解決這個問題的兩種思路(使用UIButton控件)

一、利用NSTimer計時器

1.新建一個UIButton按鈕,設置成屬性,名爲codeButton。(UIButton樣式一定要爲自定義,否則後面倒計時數秒時會出現閃爍現象)

2.定義一個NSTimer的屬性,名爲timer,同時定義一個用於計時的int變量time,設置初始值爲60。

//啓動一個定時器
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(operatePerSecond) userInfo:nil repeats:YES];
 
//實現定時器中的方法
- (void)operatePerSecond {
    if (time == 1) {
      [self.timer invalidate];
      time = 60;
      [self.codeButton setTitle:@"重新獲取" forState:UIControlStateNormal];
      self.codeButton.tintColor = [UIColor blackColor];
      self.codeButton.enabled = YES;
    }else {
      time --;
      [self.codeButton setTitle:[NSString stringWithFormat:@"%ds" ,time] forState:UIControlStateNormal];
    }
}

3.此時主要邏輯已經完成,但要記得:在本頁面即將消失的時候也要停掉計時器self.timer。

二、利用GCD實現

1.定義一個用於計時的time(此時要用block修飾)---  block int time = 60;

  //倒計時時間
  __block int timeout = 60;
  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_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
  dispatch_source_set_event_handler(timer, ^{
    if(timeout == 1){
      //倒計時結束,關閉
      dispatch_source_cancel(timer);
      dispatch_async(dispatch_get_main_queue(), ^{
      timeout = 60;
      [self.codeButton setTitle:@"重新獲取" forState:UIControlStateNormal];
      self.codeButton.tintColor = [UIColor blackColor];
      self.codeButton.enabled = YES;
      });
    }else{
      NSString *strTime = [NSString stringWithFormat:@"%ds",timeout];
      dispatch_async(dispatch_get_main_queue(), ^{
        [self.codeButton setTitle:strTime forState:UIControlStateNormal];
      });
      timeout--;
    }
  });
dispatch_resume(timer);

2.把上述代碼寫入點擊方法中即可實現倒計時效果。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章