iOS 倒计时NSTimer

项目中可能会遇到有些倒计时的地方

比方 手机验证的时候,验证码一般都会有一个时间限制,此时在输入验证码的地方就须要展示一个倒计时


详细实现方式是使用了iOS 自带的 NSTimer


上代码

首先新建


    int secondsCountDown; //倒计时总时长
    NSTimer *countDownTimer;
    UILabel *labelText;


然后详细实现


    //创建UILabel 加入到当前view
    labelText=[[UILabel alloc]initWithFrame:CGRectMake(10, 120, 120, 36)];
    [self.view addSubview:labelText];
    
    //设置倒计时总时长
    secondsCountDown = 60;//60秒倒计时
    //開始倒计时
    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
    
    //设置倒计时显示的时间
    labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];

实现每秒钟运行的方法

-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //改动倒计时标签现实内容
    labelText.text=[NSString stringWithFormat:@"%d",secondsCountDown];
    //当倒计时到0时。做须要的操作,比方验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        [labelText removeFromSuperview];
    }
}


大致已经实现,有问题可继续交流


苹果开发群 :414319235  欢迎增加  欢迎讨论问题






原文地址:https://www.cnblogs.com/gavanwanggw/p/6791715.html