在上一个项目中有使用到验证码倒计时功能,之前同事的做法是直接使用NSTimer,比较严重的bug是app计入后台之后倒计时就暂停,重新进入前台才有倒计时,在网上看到使用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);
//每秒执行
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:@"重新发送" 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];
}
网友评论