ios - NSTimer 毫秒倒计时

标签 ios nstimer countdown milliseconds

我想用秒和毫秒进行简单的倒计时:SS:MM。 但是,我想在计时器到达 0:00 时停止计时器或执行某些操作。 目前计时器正在工作,但不会在 0:00 停止。我可以让秒停止,但不能让毫秒停止。怎么了?

-(void) setTimer {
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton];
    tmp.milisecondsCount = 99;
    tmp.secondsCount = 2;



    tmp.countdownTimerGame = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];


}

-(void) timerRun {
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton];
    tmp.milisecondsCount = tmp.milisecondsCount - 1;



    if(tmp.milisecondsCount == 0){
        tmp.secondsCount -= 1;

        if (tmp.secondsCount == 0){

            //Stuff for when the timer reaches 0
            //Also, are you sure you want to do [self setTimer] again
            //before checking if there are any lives left?

            [tmp.countdownTimerGame invalidate];
            tmp.countdownTimerGame = nil;
            tmp.lives = tmp.lives - 1;
            NSString *newLivesOutput = [NSString stringWithFormat:@"%d", tmp.lives];
            livesLabel.text = newLivesOutput;
            if (tmp.lives == 0) {
                [self performSelector:@selector(stopped) withObject:nil];

            }
            else {[self setTimer]; }
        }
        else

            tmp.milisecondsCount = 99;
    }


    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%2d", tmp.secondsCount, tmp.milisecondsCount];

    timeLabel.text = timerOutput;






}



-(void) stopped {
    NSLog(@"Stopped game");
    timeLabel.text = @"0:00";

}

最佳答案

嗯。你做

tmp.milisecondsCount = tmp.milisecondsCount - 1;
if(tmp.milisecondsCount == 0){
    tmp.milisecondsCount = 100;
    tmp.secondsCount -= 1;
}

紧接着

if ((tmp.secondsCount == 0) && tmp.milisecondsCount == 0) {
   //stuff
}

如果 milisecond 达到 0 后立即将其重置为 100,它们怎么可能都为 0?

编辑:改为做类似的事情:

if(tmp.milisecondsCount < 0){
    tmp.secondsCount -= 1;
    if (tmp.secondsCount == 0){
        //Stuff for when the timer reaches 0
        //Also, are you sure you want to do [self setTimer] again
        //before checking if there are any lives left?
    }
    else
        tmp.milisecondsCount = 99; 
}

关于ios - NSTimer 毫秒倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19050918/

相关文章:

C++ 游戏倒计时

javascript - 圣诞节前的购物日柜台 jQuery

objective-c - 以日/月/年格式显示特定日期的倒计时

ios - SocketIOClient-Swift : Unable to authenticate socket server

ios - UIModalPresentationFormSheet 的圆角

iphone - 使用 NSTimer 的序列动画

ios - 使用 NSTimer 时如何更改 userInfo 中的数据?

ios - 后台线程上的NSTimer回调

ios - 为什么这个变量被认为不是数字

iphone - UITableViewCell 不显示文本