美文网首页
iOS项目中获取验证码倒计时及闪烁问题解决方案

iOS项目中获取验证码倒计时及闪烁问题解决方案

作者: 做个稻草人 | 来源:发表于2018-04-17 12:31 被阅读0次

    大家在做验证码的时候一般都会用到倒计时,基本上大家实现的方式都差不多,先贴出一些代码来..

    -(void)startTime{

        __block int timeout= 59; //倒计时时间

        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.getIdentifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];

                    self.getIdentifyBtn.userInteractionEnabled = YES;

                });

            }else{

                //            int minutes = timeout / 60;

                int seconds = timeout % 60;

                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];

                dispatch_async(dispatch_get_main_queue(), ^{

                    //设置界面的按钮显示 根据自己需求设置

                    [UIView beginAnimations:nil context:nil];

                    [UIView setAnimationDuration:1];

                    [self.getIdentifyBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];

                    [UIView commitAnimations];

                    self.getIdentifyBtn.userInteractionEnabled = NO;

                });

                timeout--;

            }

        });

        dispatch_resume(_timer);

    }

     上面代码的btn是我自己的,看客们根据自己项目来修改,那么还有一个问题,有时候用xib创建了按钮,做了倒计时,你会发现按钮倒计时的时候会发生闪烁的问题,那么解决方法是:

    修改你的button的属性,如果是xib很简单,直接到button的属性中把按钮由默认的system改成custom即可,如果是代码创建,在创建的时候用

    self.smsButton = [UIButton createButtonWithStyle:UIButtonTypeRoundedRect  

    withFrame:CGRectMake(80,0,100,30)  

    withTitle:NSLocalizedString(@"重发验证码", nil)  

                     withTitleColor:color  

    withBackgroudColor:nil  

    withNormalImage:nil  

    withHighlightedImage:nil  

    withNormalBackgroudImage:nil  

                                           }];  

    不可直接设置buttontype因为buttontype属性是readonly的!!!

    来自 https://www.cnblogs.com/changjianioser/p/5076826.html

    相关文章

      网友评论

          本文标题:iOS项目中获取验证码倒计时及闪烁问题解决方案

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