标签:
在ios中我们在做验证码的时候 就少不了要用到倒计时 所以 这里就介绍两种实现倒计时的方法
第一种是使用NSTimer方式实现:
@implementation SYViewController { int totalSeconds; NSTimer *downTimer; UILabel *labelText; } - (void)viewDidLoad { [super viewDidLoad]; totalSeconds = 60; labelText = [[UILabel alloc] init]; labelText.frame = CGRectMake(100, 100, 300, 30); [self.view addSubview:labelText]; downTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerChange) userInfo:nil repeats:YES]; labelText.text = [NSString stringWithFormat:@"%d",totalSeconds]; } - (void)timerChange { totalSeconds--; labelText.text = [NSString stringWithFormat:@"%d",totalSeconds]; if (totalSeconds==0) { [downTimer invalidate]; downTimer = nil; } } }
第二种方式 使用GCD的方式实现:
__block int timeout=60; //倒计时时间 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(), ^{ //设置界面的按钮显示 根据自己需求设置 labelText.text = @"倒计时结束"; }); }else{ int minutes = timeout / 60; int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新获取验证码",minutes, seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 labelText.text = [NSString stringWithFormat:@"%@",strTime]; }); timeout--; } }); dispatch_resume(_timer);
标签:
原文地址:http://www.cnblogs.com/syios/p/5925498.html