zoukankan      html  css  js  c++  java
  • 倒计时功能的实现

    在ios中我们在做验证码的时候 就少不了要用到倒计时 所以 这里就介绍两种实现倒计时的方法

    第一种是使用NSTimer方式实现:

    @implementation SYViewController
    {
        int totalSeconds;
        NSTimer *downTimer;
        UILabel *labelText;
    }
    
    - (void)viewDidLoad {
        
        [super viewDidLoad];
        
        totalSeconds = 60;
        
        labelText = [[UILabel alloc] init];
        labelText.frame = CGRectMake(100, 100, 300, 30);
        [self.view addSubview:labelText];
        downTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerChange) userInfo:nil repeats:YES];
        labelText.text = [NSString stringWithFormat:@"%d",totalSeconds];
    
    }
    
    - (void)timerChange
    {
        totalSeconds--;
        labelText.text = [NSString stringWithFormat:@"%d",totalSeconds];
    
        if (totalSeconds==0) {
            [downTimer invalidate];
            downTimer = nil;
        }
    }
    
    }

    第二种方式 使用GCD的方式实现:

       __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(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    labelText.text = @"倒计时结束";
                });
            }else{
                int minutes = timeout / 60;
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新获取验证码",minutes, seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    labelText.text = [NSString stringWithFormat:@"%@",strTime];
                    
                });
                timeout--;
                
            }
        });
        dispatch_resume(_timer);
  • 相关阅读:
    regex c语言
    gitlab qq邮箱的配置
    error adding symbols: DSO missing from command line
    gcc 错误 //usr/lib/x86_64-linux-gnu/libstdc++.so.6 ...
    autogen.sh 的使用
    caffe_ssd create_data.sh 遇到的问题
    Ubuntu Server 中文乱码解决方案
    error: subprocess paste was killed by signal (Broken pipe)
    AttributeError: 'module' object has no attribute 'RAND_LIMIT_swigconstant
    eclipse:No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]
  • 原文地址:https://www.cnblogs.com/syios/p/5925498.html
Copyright © 2011-2022 走看看