溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

iOS如何實現短信驗證碼倒計時

發布時間:2021-05-24 11:59:29 來源:億速云 閱讀:260 作者:小新 欄目:移動開發

小編給大家分享一下iOS如何實現短信驗證碼倒計時,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

一、利用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.把上述代碼寫入點擊方法中即可實現倒計時效果。

以上是“iOS如何實現短信驗證碼倒計時”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

ios
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女