2011-09-30 61 views
1

我試圖實現一個按鈕,在隨機時間段(0-10s之間)後啓動一個定時器。計時器運行時,它應該每0.005秒更新一次標籤以顯示已經過了多長時間。我遇到的問題是2倍:等待隨機時間,然後開始更新UILabel(iPhone)中的流逝時間

  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)如何修復凍結了應用

的「延遲」時期......因爲我在這一點上幾乎難倒這將是非常有益的。提前致謝。

+0

sleep()阻止執行 – EricLeaf

回答

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。希望有助於!

+0

感謝您對此的幫助。我很新的iPhone開發,我不知道我完全明白scheduledTimerWithTimeInterval究竟做了什麼。我查看了API描述,並且我知道它會根據提供的參數返回另一個NSTimer對象;但是我不明白如何從這個新對象中獲取流逝的時間。 –

+0

所有'NSTimer'都會在指定時間後調用一個方法(@selector()中的方法)。因此,如果您想在固定時間後更新某些內容,則只需調用上述方法即可。 – msgambel

+0

感謝您的解釋,我設法得到了我使用兩個答案的組合後的效果! –

1

的答案,可能是:

一旦時間的隨機量已經過去了,(@MSgambel有一個很好的建議),然後執行:

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

(以上線路可以進入@ MSgambel's -text2方法。)

這將每秒重複調用-periodicallyUpdateLabel方法一次。在這種方法中,你可以做更新標籤,檢查用戶操作,或者如果時間到了或者其他條件滿足,就結束遊戲。

這裏是-periodicallyUpdateLabel方法:

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

你必須將文本格式不同,以得到你想要的。另外,從計數器值轉換爲使用kGranularity的時間。但是,這是我發現的,iOS設備中只有很多CPU週期。試圖降低到微秒級別使界面變得呆滯,顯示的時間開始偏離實際時間。換句話說,您可能不得不將標籤的更新限制爲每百分之一秒或十分之一。實驗。

+0

這真的很有幫助 - 謝謝。我能夠結合這兩個答案來獲得我期待的效果。再次感謝! –