停止并重置NSTimer [英] Stop and Reset NSTimer

查看:113
本文介绍了停止并重置NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的计时器使用,通过按下按钮激活。它从60到0没有问题,但我想要的是停止并重置按钮上的计时器。我使用下面的代码按下按钮时设法停止它但由于某种原因无法让它重置并停在60.这应该很简单,但它不起作用。有什么建议吗?

I have a simple timer using that is activated with a button is pushed. It runs from 60 to 0 no problem but what I want is to stop and reset the timer on push button. I have managed to stop it when the button is pressed using the code below but for some reason cannot get it to reset and stop at 60. This should be simple but it isn't working. Any suggestions?

使用简单操作设置计时器

- (IBAction)timerStart:(id)sender {

if(!secondCounter == 0){
        [countdownTimer invalidate];
    }
    else {
           [self setTimer];
     }
}

定时器代码

- (void)timerRun {
    secondCounter = secondCounter - 1;
    int minutes = secondCounter;

    NSString *timerOutput = [NSString stringWithFormat:@"%d", minutes ];
    countDownLabel.text = timerOutput;

    if(secondCounter == 0){
        [countdownTimer invalidate];
        countdownTimer = nil;
    }
}

- (void)setTimer {
    secondCounter = 60;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];

}


推荐答案

做什么你的意思是停止计时器?计时器不会停止。您希望 countDownLabel.text 显示60?当你使计时器无效时它将停止运行并调用 timerRun 方法如果你想重启计时器,只需调用 setTimer function再次。我想你的意思是在 [countdownTimer invalidate]; 之后 countDownLabel.text = @60再次单击该按钮,计时器将再次启动,并将更改标签。如果您正在寻找,请告诉我。

What do you mean to stop the timer? Timer is not going to stop. You would like to have to have countDownLabel.text to show 60? When you invalidate the timer it will stop running and calling timerRun method If you want to restart the timer just call setTimer function again. I think what you meant is to have countDownLabel.text = @"60" after [countdownTimer invalidate]; and when you click the button again the timer will start again and will change the label. Let me know if this is what you were looking for.

正如克里斯蒂安所说,你必须重置第二个计数器

As Christian said you have to reset the secondCounter

secondCounter = 0;

这篇关于停止并重置NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆