2011-06-16 44 views
0

我正在爲iPhone開發應用程序。我的問題是如何每0.5秒顯示一個不同文本的新標籤。例如,它會顯示藍色,紅色,綠色,橙色和紫色;一個接一個。現在我正在這樣做:標籤顯示不能與iPhone應用程序即時通訊

results = aDictionary; 
    NSArray *myKeys = [results allKeys]; 
    NSArray *sortedKeys = [myKey sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 
    int keyCount = [sortedKeys count]; 
    while (flag == NO) { 


     NSTimeInterval timeMS = [startDate timeIntervalSinceNow] * -10000.0;    

     if (timeMS >= i) { 
      ii++; 
      i += 1000; 
      NSLog(@"endDate = %f", timeMS); 
      int randomNumber = rand() % keyCount + 1; 
      lblResult.text = [results valueForKey:[sortedKeys objectAtIndex:(randomNumber - 1)]]; 
      result = [results valueForKey:[sortedKeys objectAtIndex:(randomNumber - 1)]]; 
      lblResult.text = result; 

     } 
     if (ii > 25) { 
      flag = YES; 
     } 
    } 
    lblResult.text = [results valueForKey:[sortedKeys objectAtIndex:(sortedKeys.count - 1)]]; 

此函數在viewDidAppear函數中調用,並且當前不顯示新標籤。它只顯示最後一個。我做錯了什麼?什麼是最好的方法來解決這個問題?

+0

[中的中間爲()循環更新的UILabel]的可能重複(http://stackoverflow.com/問題/ 6363828 /更新 - 用於循環的中間的uilabel) – 2011-06-17 00:59:54

+0

另外[動態更新UILabel](http://stackoverflow.com/questions/6336991/dynamically-updating-a-uilabel )和[文本字段等待,直到循環結束更新](http://stackoverflow.com/questio ns/5829977 /)和[更改標籤文本的循環](http://stackoverflow.com/questions/6325202/objective-c-loop-to-change-label-text)和[調用睡眠和更新文本字段不起作用](http://stackoverflow.com/questions/5834062/calling-sleep5-and-updating-text-field-not-working) – 2011-06-17 01:01:16

回答

0

問題是你沒有給運行循環一個運行的機會(因此,繪圖發生)。您需要使用定期觸發的NSTimer,並設置下一個文本(您可以在當前所在的實例變量中記住)。

或者使用這樣的(假設項目是NSArray牽着你的字符串):

- (void)updateText:(NSNumber *)num 
{ 
    NSUInteger index = [num unsignedInteger]; 
    [label setText:[items objectAtIndex:index]]; 
    index++; 

    // to loop, add 
    // if (index == [items count]) { index = 0; } 

    if (index < [items count]) { 
     [self performSelector:@selector(updateText:) withObject:[NSNumber numberWithUnsignedInteger:index] afterDelay:0.5]; 
    } 
} 

在開始的時候(例如,在viewDidAppear:),然後你可以調用

[self updateText:[NSNumber numberWithUnsignedInteger:0]]; 

來觸發最初的更新。

當然你需要確保當你的視圖消失時執行不會繼續,你可以通過取消performSelector來實現,或者如果你正在使用計時器,只需使其失效或者使用布爾值或...

如果你想獲得真正看中的,使用GCD :)

+0

非常感謝!這工作完美。 – 2011-06-17 18:47:17