1

我正在尝试制作倒计时标签,但它并没有减少..任何人都可以发现代码中的错误

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

4 回答 4

6

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

您必须在启动 Timer 时设置 secondsLeft 的值,并在 timer 上递减它

- (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];
于 2013-01-25T11:04:22.583 回答
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];
    }
}
于 2013-01-25T11:14:25.340 回答
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--;
}
于 2013-01-25T11:01:18.043 回答
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];

}
于 2013-01-25T11:45:41.797 回答