您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 驗證碼倒數計時效果實作

編輯:iOS 開發綜合

需求說明

在發送驗證碼後,按鈕通常會進入倒數狀態,倒數期間不可重複點擊,倒數結束後再恢復為可點擊狀態。以下使用 dispatch_source 建立每秒觸發的計時器。

倒數計時範例

-(void)fireTimer {
    __block int timeout = 180;
    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, ^{
        if (timeout == 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_changeCodeButton setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
                _changeCodeButton.userInteractionEnabled = YES;
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"%d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_changeCodeButton setTitle:[NSString stringWithFormat:@"(%@s)後重新獲取", strTime] forState:UIControlStateNormal];
                _changeCodeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });

    dispatch_resume(timer);
}

注意事項

這種寫法在畫面跳轉或頁面重建後,計時器通常會被重置。若希望跨頁面持續倒數,建議將剩餘秒數與計時狀態交由全域物件管理,例如單例、全域計時器或背景任務,再於前台顯示時同步剩餘時間。

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