主要用于項目中獲取驗證碼環(huán)節(jié),參考了之前搜索的網(wǎng)絡(luò)資料,權(quán)作記錄.
TimerCountDown.h文件內(nèi):
#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 文件內(nèi):
#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) {
//倒計時結(jié)束
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秒后重發(fā)",seconds] forState:UIControlStateNormal];
[inButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
inButton.userInteractionEnabled = NO;
}];
});
timeout--;
}
});
dispatch_resume(_timer);
}
@end
使用方式:
1.導(dǎo)入頭文件
#import "TimerCountDown.h"
2.在獲取驗證碼按鈕的點擊事件內(nèi):
- (IBAction)test:(id)sender {
[TimerCountDown startCountDown:sender duration:10];
}