1

我正在尝试实现一个在随机时间段(0-10 秒之间)后启动计时器的按钮。当计时器运行时,它应该每 0.005 秒更新一个标签以显示已经过去了多少时间。我遇到的问题是 2 倍:

  1. 我不确定如何让标签每 0.005 秒更新一次经过的时间。

  2. 我无法让应用程序在启动计时器之前等待随机时间。目前我正在使用,sleep(x)但它似乎导致应用程序忽略if语句中的所有其他代码并导致按钮图像冻结(即看起来它仍然被点击)。

这是我到目前为止的代码......

- (IBAction)buttonPressed:(id)sender
{
    if ([buttonLabel.text isEqualToString:@"START"]) 
    {
        buttonLabel.text = @" "; // Clear the label
        int startTime = arc4random() % 10; // Find the random period of time to wait
        sleep(startTime); // Wait that period of time
        startTime = CACurrentMediaTime();  // Set the start time
        buttonLabel.text = @"STOP"; // Update the label
    }
    else
    {
        buttonLabel.text = @" ";
        double stopTime = CACurrentMediaTime(); // Get the stop time
        double timeTaken = stopTime - startTime; // Work out the period of time elapsed
    }
}

如果有人对..有任何建议

A)如何让标签随着经过的时间而更新。

或者

B)如何解决冻结应用程序的“延迟”期

......这真的很有帮助,因为我在这一点上非常难过。提前致谢。

4

2 回答 2

3

您应该使用NSTimer来执行此操作。试试代码:

- (void)text1; {
  buttonLabel.text = @" ";
}

- (void)text2; {
  buttonLabel.text = @"STOP";
}

- (IBAction)buttonPressed:(id)sender; {
  if ([buttonLabel.text isEqualToString:@"START"]) {
    int startTime = arc4random() % 10; // Find the random period of time to wait
    [NSTimer scheduledTimerWithTimeInterval:(float)startTime target:self selector:@selector(text2:) userInfo:nil repeats:NO];
  }
  else{
    // I put 1.0f by default, but you could use something more complicated if you want.
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(text1:) userInfo:nil repeats:NO];
  }
}

我不确定您要如何根据时间更新标签,但是如果您发布更多代码或举个例子,我将发布有关如何执行此操作的代码,但它也只会NSTimer使用. 希望有帮助!

于 2011-09-30T17:14:29.530 回答
1

A的答案可能是:

一旦随机时间过去,(@MSgambel 有一个很好的建议),然后执行:

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

(上面的行可以进入@MSgambel 的 -text2 方法。)

这将每秒钟重复调用-periodicallyUpdateLabel一次该方法。kGranularity在该方法中,您可以执行更新标签、检查用户操作或在时间到或满足其他条件时结束游戏等操作。

这是-periodicallyUpdateLabel方法:

- (void)periodicallyUpdateView {
    counter++;
    timeValueLabel.text = [NSString stringWithFormat:@"%02d", counter];
}

您必须以不同的方式格式化文本才能获得所需的内容。此外,使用 kGranularity 从计数器值转换为时间。但是,这就是我发现的,iOS 设备中只有这么多的 cpu 周期。试图下降到微秒级导致界面迟缓,显示的时间开始偏离实际时间。换句话说,您可能必须将标签的更新限制为每百分之一秒或十分之一。实验。

于 2011-09-30T17:34:37.537 回答