计时器NSTimer

来源:互联网 发布:淘宝模特小兮 编辑:程序博客网 时间:2024/04/30 12:40

//局部变量

    int secondsCountDown; //倒计时总时长

    NSTimer *countDownTimer;

    UILabel *labelText;



-(void)createDaoJiShi{

    //创建UILabel添加到当前view

    labelText=[[UILabelalloc]initWithFrame:CGRectMake(10,120, 120, 36)];

    [self.viewaddSubview:labelText];

    

    //设置倒计时总时长

    secondsCountDown =60;//60秒倒计时

    //开始倒计时

    countDownTimer = [NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(timeFireMethod)userInfo:nilrepeats:YES];//启动倒计时后会每秒钟调用一次方法 timeFireMethod

    

    //设置倒计时显示的时间

    labelText.text=[NSStringstringWithFormat:@"%d",secondsCountDown];

}

-(void)timeFireMethod{

    //倒计时-1

    secondsCountDown--;

    //修改倒计时标签现实内容

    labelText.text=[NSStringstringWithFormat:@"%d",secondsCountDown];

    //当倒计时到0时,做需要的操作,比如验证码过期不能提交

    if(secondsCountDown==0){

        [countDownTimerinvalidate];

        [labelTextremoveFromSuperview];

    }

}


0 0