等待随机时间,然后开始更新UILabel (iPhone)中的运行时间



我试图实现一个按钮,启动一个定时器后的随机时间段(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)如何修复冻结应用程序的"延迟"期

…这真的很有帮助,因为我在这一点上几乎被难住了。

您应该使用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为好。希望有帮助!

A的答案可能是:

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

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

(上面这行可以放到@MSgambel的-text2方法中)

将每kGranularity秒重复调用一次-periodicallyUpdateLabel方法。在这种方法中,你可以更新标签,检查用户行为,或者在时间到了或满足其他条件时结束游戏。

下面是-periodicallyUpdateLabel方法:

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

你必须改变文本的格式才能得到你想要的。另外,使用kGranularity将计数器值转换为时间。然而,我发现iOS设备的cpu周期是有限的。尝试降低到微秒级别会使界面变得缓慢,并且显示的时间开始偏离实际时间。换句话说,您可能必须将标签的更新限制为每百分之一秒或十分之一秒一次。实验。

最新更新