我正在尝试实现一个按钮,该按钮在一段随机时间(0-10秒之间)后启动计时器 . 当计时器运行时,它应该每隔0.005秒更新一个标签,以显示已经过了多长时间 . 我遇到的问题是2倍:
-
我不知道如何让标签更新,每隔0.005秒经过一次 .
-
我'm having trouble getting the app to wait the random amount of time before starting timer. At present I' m使用
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)如何解决冻结应用程序的“延迟”期限
......这真的很有帮助,因为我在这一点上非常难过 . 提前致谢 .
2 回答
您应该使用NSTimer来执行此操作 . 试试代码:
我发布了关于如何做到这一点的代码,但它也只是使用
NSTimer
. 希望有帮助!A的答案可能是:
一旦随机时间量过去了,(@ MSgambel有一个很好的建议),然后执行:
(上面这行可以进入@ MSgambel的-text2方法 . )
这将每隔_2947920秒重复一次
-periodicallyUpdateLabel
方法 . 在该方法中,您可以执行更新标签,检查用户操作或在时间到达或满足其他条件时结束游戏等操作 .这是
-periodicallyUpdateLabel
方法:您必须以不同方式格式化文本以获得所需内容 . 此外,使用kGranularity从计数器值转换为时间 . 然而,这就是我发现的,iOS设备中只有这么多的CPU循环 . 试图降低到微秒级别使界面变得缓慢,显示的时间开始偏离实际时间 . 换句话说,您可能必须将标签的更新限制为每百分之一秒或十分之一 . 实验 .