繁体   English   中英

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

[英]Wait for random amount of time, then start updating elapsed time in a 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方法。)

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

这是-periodicallyUpdateLabel方法:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM