码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-02-28 22:48:20      阅读:643      评论:0      收藏:0      [点我收藏+]

标签:

方法一:

- (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真个跟着一起跳动,而不是单单数字跳动。

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

标签:

原文地址:http://www.cnblogs.com/junpengliu/p/5225688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!