dispatch倒計時的實現

主要用于項目中獲取驗證碼環節,參考了之前搜索的網絡資料,權作記錄.
TimerCountDown.h文件內:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface TimerCountDown : NSObject

/**
 倒計時<獲取驗證碼>
 @param inButton 獲取驗證碼的點擊按鈕
 @param duration 倒計時時長
 */
+ (void)startCountDown:(UIButton *)inButton duration:(NSInteger)duration;
@end

TimerCountDowm.m 文件內:

#import "TimerCountDown.h"

@implementation TimerCountDown

+ (void)startCountDown:(UIButton *)inButton duration:(NSInteger)duration {
    
    __block NSInteger timeout = duration;
    
    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(), ^{
                [inButton setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
                [inButton setTitleColor:[UIColor colorWithRed:39/255.0 green:138/255.0 blue:228/255.0 alpha:1] forState:UIControlStateNormal];
                inButton.userInteractionEnabled = YES;
            });
        } else {
            //正在倒計時
            NSInteger seconds = timeout % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:1 animations:^{
                    [inButton setTitle:[NSString stringWithFormat:@"%ld秒后重發",seconds] forState:UIControlStateNormal];
                    [inButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                    inButton.userInteractionEnabled = NO;
                }];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end

使用方式:
1.導入頭文件

#import "TimerCountDown.h"

2.在獲取驗證碼按鈕的點擊事件內:

- (IBAction)test:(id)sender {
    [TimerCountDown startCountDown:sender duration:10];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,559評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,257評論 4 61
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 我們常常發現,銷售人員已經整理好了客戶資料,目標客戶也選擇與確定下來,但是,在準備拜訪客戶前,卻遭到了客戶的直接拒...
    奮斗的番茄閱讀 927評論 0 0
  • ps這是一篇沒頭沒腦的文章 單純自己明志 苦笑臉。 時間是一個不折不扣的小偷。 我還清楚記得你說,巴啦啦考試還有半...
    陶瓷姑娘閱讀 478評論 0 0