美文网首页iOS开发
iOS 验证码倒计时

iOS 验证码倒计时

作者: 风规自远 | 来源:发表于2018-09-07 16:28 被阅读2次

    /**

     倒计时方法 在点击获取验证码按钮的方法里调用此方法即可实现, 需要在倒计时里修改按钮相关的请在此方法里yourButton修改

     */

    + (void)sentPhoneCodeTimeMethod:(UIButton*)btn {

        //倒计时时间 - 60S

        __blockNSIntegertimeOut =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(), ^{

                    // 倒计时结束

                    [btnsetBackgroundColor:ZTCOLOR];

                    [btnsetTitle:@"重发验证码"forState:UIControlStateNormal];

                    [btnsetTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

                    [btnsetEnabled:YES];

                    [btnsetUserInteractionEnabled:YES];

                });

            }else{

                //开始计时

                //剩余秒数 seconds

                NSIntegerseconds = timeOut %60;

                NSString*strTime = [NSStringstringWithFormat:@"%.1ld", seconds];

                //主线程设置按钮样式

                dispatch_async(dispatch_get_main_queue(), ^{

                    [UIView beginAnimations:nil context:nil];

                    [UIView setAnimationDuration:1.0];

                    NSString*title = [NSStringstringWithFormat:@"%@",strTime];

                    [btnsetTitle:title forState:UIControlStateNormal];

                    [btnsetContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

                    [btnsetTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

                    [btnsetBackgroundColor:RGBACOLOR(212,212,212,1)];

                    [UIView commitAnimations];

                    //计时器间不允许点击

                    [btnsetUserInteractionEnabled:NO];

                });

                timeOut--;

            }

        });

        dispatch_resume(timer);

    }

    相关文章

      网友评论

        本文标题:iOS 验证码倒计时

        本文链接:https://www.haomeiwen.com/subject/kticgftx.html