ios开发获取验证码按钮读秒效果

方法一:

- (void)startCountDown
{
    _seconds = 60;
    NSString *str = [NSString stringWithFormat:@"%d秒后可重新获取", _seconds];
    [_btnVerify setTitle:str forState:UIControlStateDisabled];
    [_btnVerify.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [_btnVerify setEnabled:NO];
    _clockTimer = [NSTimer timerWithTimeInterval:1
                                          target:self
                                        selector:@selector(oneSecondPass)
                                        userInfo:nil
                                         repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_clockTimer forMode:NSDefaultRunLoopMode];
}

- (void)oneSecondPass
{
    if (_seconds > 0)
    {
        _seconds = _seconds - 1;
        NSString *str = [NSString stringWithFormat:@"%d秒后可重新获取", _seconds];
        [_btnVerify setTitle:str forState:UIControlStateDisabled];
    } else {
        [_clockTimer invalidate];
        _clockTimer = nil;
        [_btnVerify.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_btnVerify setEnabled:YES];
        
    }
}

方法2:

-(void)startTime{
    __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(), ^{
                [_btnVerify setTitle:@"重新发送验证码" forState:UIControlStateNormal];
                _btnVerify.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{

                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_btnVerify setTitle:[NSString stringWithFormat:@"%zd秒后重新发送",timeout] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _btnVerify.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

}

需要注意的是,获取验证码button的type要设为Custom。
如果设为system,button的title真个跟着一起跳动,而不是单单数字跳动。

posted on 2016-02-28 21:31  鹏哥的技术博客  阅读(1767)  评论(0)    收藏  举报