2011-10-25 28 views
3

在buttonClicked方法中,我想將UILabel中的文本顏色設置爲黑色,等待三秒鐘,然後將顏色設置爲綠色。但是,標籤永遠不會變黑。該方法等待三秒鐘,然後UILabel文本變爲綠色。我認爲使用performSelectorOnMainThread會解決這個問題,但它沒有。代碼如下。非常感謝,如果我錯過了一些明顯的事情,我很抱歉。IOS buttonClick並更新視圖

喬恩R.

-(void) buttonClicked: (id) sender 
{ 
    // (UILabel *) letterLabel is instance variable of TestProgramDelegate 

    [letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES]; 

    [NSThread sleepForTimeInterval:3]; 

    [letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES]; 
} 
+0

你最終解決了這個問題嗎? – bryanmac

回答

2

你的方法改變顏色同步的兩倍。所有這些代碼都在主線程上執行。

// run on main thread 
[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES]; 

// buttonClicked: called on mainThread so this is on main thread 
[NSThread sleepForTimeInterval:3]; 

// also on main thread ... 
[letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES]; 

UI主線程循環並尋找代碼以基於按鈕點擊等事情觸發。一旦檢測到點擊,您的方法就會執行,設置顏色,等待三秒鐘,然後再次設置顏色,然後重新繪製UI主循環。由於用戶界面不會在兩者之間重繪,因此您從不會看到第一個。

如果你想這樣做,你需要設置顏色,然後在後臺線程上,等待三秒鐘,然後回調主線程來更新用戶界面。

這是一個相關的帖子:

GCD, Threads, Program Flow and UI Updating

+0

@邁克爾,非常感謝!您的意見和相關帖子完全爲我解決了。 –

+0

應該是bryanmac :)但不客氣。你必須把你的腦袋繞過異步的東西... – bryanmac

0

- (void)buttonClicked:(id)sender將在主線程中,所以它混淆爲什麼您使用[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];當上下文已經在主線程中調用。

[letterlabel setBackgroundColor:[UIColor blackColor]];應該是你按下按鈕時需要調用的所有東西。

您可以使用NSTimer或本地通知回調將顏色更改爲綠色。將主線程放置在應用程序中通常不是一個好主意。

希望有幫助!

+0

你是對的,我濫用了performSelectorOnMainThread。謝謝你的幫助! –