[英]Wait for random amount of time, then start updating elapsed time in a UILabel (iPhone)
我正在嘗試實現一個按鈕,該按鈕在一段隨機時間(0-10秒之間)后啟動計時器。 當計時器運行時,它應該每隔0.005秒更新一個標簽,以顯示已經過了多長時間。 我遇到的問題是2倍:
我不知道如何讓標簽更新,每隔0.005秒經過一次。
我無法讓應用程序在啟動計時器之前等待一段隨機時間。 目前我正在使用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.