计时器发送验证码(倒计时实现)

建立验证码按钮

//发送验证码按钮
        _sentCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 27 - 4 - 94, CGRectGetMinY(_registerCodeFD.frame) + 4, 94, 40)];
        [_sentCodeBtn setBackgroundColor:colorWithRGBA(0, 191, 191, 0.9)];
        [_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        [_sentCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]];
        //设置圆角
        [_sentCodeBtn.layer setCornerRadius:3.0f];
        [_sentCodeBtn.layer setShouldRasterize:YES];
        [_sentCodeBtn.layer setRasterizationScale:[UIScreen mainScreen].scale];
        //发送事件
        [_sentCodeBtn addTarget:self action:@selector(sentCodeMethod) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_sentCodeBtn];

核心代码,实现点击后倒计时效果

//发送验证码
-(void)sentCodeMethod{
    NSLog(@"发送验证码。。");
    //计时器发送验证码
    [self sentPhoneCodeTimeMethod];
    //调用发送验证码接口-》

}

//计时器发送验证码
-(void)sentPhoneCodeTimeMethod{
    //倒计时时间 - 60秒
    __block NSInteger timeOut = 59;
    //执行队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //计时器 -》dispatch_source_set_timer自动生成
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeOut <= 0) {
            dispatch_source_cancel(timer);
            //主线程设置按钮样式-》
            dispatch_async(dispatch_get_main_queue(), ^{
                [_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                [_sentCodeBtn setUserInteractionEnabled:YES];
            });
        }else{
            //开始计时
            //剩余秒数 seconds
            NSInteger seconds = timeOut % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
            //主线程设置按钮样式
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1.0];
                [_sentCodeBtn setTitle:[NSString stringWithFormat:@"%@S后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                //计时器件不允许点击
                [_sentCodeBtn setUserInteractionEnabled:NO];
            });
            timeOut--;
        }
    });
    dispatch_resume(timer);
}

转载自:http://blog.csdn.net/qxuewei/article/details/51143081



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值