iOS項目中獲取驗證碼倒計時及閃爍問題解決方案


大家在做驗證碼的時候一般都會用到倒計時,基本上大家實現的方式都差不多,先貼出一些代碼來..

 

-(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的!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM