Untitled.gif
在上一個項目中有使用到驗證碼倒計時功能涩拙,之前同事的做法是直接使用NSTimer唉擂,比較嚴重的bug是app計入后臺之后倒計時就暫停想帅,重新進入前臺才有倒計時,在網(wǎng)上看到使用GCD山叮,完美解決bug著榴,自己嘗試做了一個demo,主要代碼如下:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
// 開啟倒計時效果
-(void)open{
//倒計時時間(秒)
__block NSInteger time = 20;
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);
//每秒執(zhí)行
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
__weak typeof(self) weakself = self;
dispatch_source_set_event_handler(_timer, ^{
if(time <= 0){ //倒計時結束屁倔,關閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
[weakself.codeBtn setTitle:@"重新發(fā)送" forState:UIControlStateNormal];
weakself.codeBtn.enabled = YES;
});
}else{
int seconds = time % 60;
dispatch_async(dispatch_get_main_queue(), ^{
//設置按鈕顯示讀秒效果
[weakself.codeBtn setTitle:[NSString stringWithFormat:@"%ds", seconds] forState:UIControlStateNormal];
weakself.codeBtn.enabled = NO;
});
time--;
}
});
dispatch_resume(_timer);
}
- (IBAction)click:(id)sender {
[self open];
}