倒计时UILabel没有减少

时间:2013-01-25 10:54:41

标签: iphone ios objective-c nstimer

我正在尝试制作倒数标签, 但它没有减少。任何人都可以在代码中找出错误

- (IBAction)start:(id)sender
{
     timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self   selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void) updateCountdown
{
     int hours, minutes, seconds;
     int secondsLeft = 30;
     hours = secondsLeft / 3600;
     minutes = (secondsLeft % 3600) / 60;
     seconds = (secondsLeft %3600) % 60;
     countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

4 个答案:

答案 0 :(得分:6)

因为每次计时器触发时都会使用相同的秒值 int secondsLeft=30;

您必须在启动计时器时设置secondsLeft的值,并在计时器

上递减它
- (IBAction)start:(id)sender{

  timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self   selector:@selector(updateCountdown) userInfo:nil repeats: YES];

  secondsLeft=30;
 }

 -(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

答案 1 :(得分:3)

您可以将secondsLefttimer声明为ivars,每次调用secondsLeft时递减updateCountdown,并在没有剩余秒数时使timer无效递减。

- (IBAction)start:(id)sender
{
    secondsLeft = 30;
    timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self   selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

- (void) updateCountdown
{
    int hours, minutes, seconds;

    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    secondsLeft--;

    if (seconds==0)
    {
        [timer invalidate];
    }
}

答案 2 :(得分:1)

您已在int secondsLeft=30;方法中指定了updateCountdown,这是正常的。

你应该将secondLeft的初始值设置在其他地方,然后在你的方法updateCountdown中你需要递减它的值

 -(void) updateCountdown {
    int hours, minutes, seconds;

    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
    if (secondsLeft > 0) secondsLeft--;
}

答案 3 :(得分:0)

我发现了问题...

-(IBAction)start:(id)sender{


countDownView.hidden=NO;

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateElapsedTime) userInfo:nil repeats:YES];
secondsLeft=30;

}



 -(void) updateCountdown {
int hours, minutes, seconds;


hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

}