Stop and Reset NSTimer

谁说胖子不能爱 提交于 2019-12-04 03:48:20

问题


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?

Timer is set using simple Action

- (IBAction)timerStart:(id)sender {

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

CODE FOR TIMER

- (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];

}

回答1:


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;



回答2:


You need to set the seconds down to 0, otherwise the you always invalidate your timer, but never start it again:

- (IBAction)timerStart:(id)sender {
    if(!secondCounter == 0) {
        [countdownTimer invalidate];
        secondCounter = 0;
    }
    else {
        [self setTimer];
    }
}


来源:https://stackoverflow.com/questions/17868825/stop-and-reset-nstimer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!