登录注册---验证码倒计时的实现

先上图:

登录注册---验证码倒计时的实现_第1张图片
WeChat_1465782264.png

OK!今天要实现的就是发送验证码的倒计时。

首先搭建好你需要的页面。给“发送验证码”sendBtn添加一个方法。
[_sendBtn addTarget:self action:@selector(startTime:) forControlEvents:UIControlEventTouchUpInside];
接下来我们就来实现倒计时

- (void)startTime:(UIButton *)_b {

    __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(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [self.btn setTitle:@"发送验证码" forState:UIControlStateNormal];
                
                self.btn.backgroundColor = COLORWITH_RGB(82, 158, 204);
                
                self.btn.userInteractionEnabled = YES;
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            int seconds = timeout % 61;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d秒后重发", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                //NSLog(@"____%@",strTime);
                
                //下面两个方法都要写上,不然会出现倒计时每一秒会闪一下的情况
                self.btn.titleLabel.text = [NSString stringWithFormat:@"%@",strTime];
                [self.btn setTitle:[NSString stringWithFormat:@"%@",strTime] forState:UIControlStateNormal];
                
                self.btn.backgroundColor = [UIColor colorWithHex:0xdadade alpha:1];
                
                self.btn.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

好了功能就已经实现了很简单吧如有问题请留言一起讨论~

你可能感兴趣的:(登录注册---验证码倒计时的实现)