2012-05-13 54 views
2

我有我想更新一個UILabel。它已通過ctrl-cicking添加到類中並通過XIB文件添加。我試圖在等待短暫的延遲後更新標籤文本。截至目前,除了下面的代碼外,沒有其他事情了。當我運行這個時,模擬器會消失一會兒,並直接轉到最新的更新文本。它不告訴我100只是200如何更新的UILabel

如何獲取標籤更新就像我希望它。最終我試圖讓一個計時器在標籤內減少。

標籤從XIB掛頭文件:

@property (strong, nonatomic) IBOutlet UILabel *timeRemainingLabel; 

在Implmentation:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.timeRemainingLabel.text = @"100"; 
    sleep(1); 
    self.timeRemainingLabel.text = @"200";  
} 
  • 已經合成。

  • 的XCode 4.3.2,Mac OSX版10.7.3,iPhone模擬器5.1(iPad上運行),iOS 5的

回答

3

的問題你的實現是執行順序不離開的方法,而在sleep。這是問題,因爲UI子系統從來沒有得到一個機會來更新標籤的"100"值它得到一個命令將其設置爲"200"之前。

爲了正確地做到這一點,首先你需要在你的init方法來創建一個定時器,像這樣:

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

然後,你需要編寫的代碼爲您updateLabel方法:

-(void) updateLabel { 
    NSInteger next = [timeRemainingLabel.text integerValue]-1; 
    timeRemainingLabel.text = [NSString stringWithFormat:@"%d", next]; 
} 
+0

感謝您的回答。這似乎做到了。 – sri

3

它永遠不會因爲你使用sleep這裏它停止向您展示100這樣你的程序的執行和sleep要更新的文字剛過1秒。如果你想這樣做,那麼你可以使用NSTimer這個。

更改上面的代碼是這樣的:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.timeRemainingLabel.text = @"100"; 

    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:NO]; 

} 

- (void) updateLabel 
{ 
    self.timeRemainingLabel.text = @"200"; 
} 
+0

謝謝回答。沒有想到這一點。 – sri

1

您的看法沒有出現,直到視圖沒有加載和標籤timeRemainingLabel的文本@"200"當這種情況發生。所以你看不到文字的變化。使用一個NSTimer要做到這一點,而不是和文本分配給在選擇標籤:

timer = [NSTimer scheduledTimerWithTimeInterval:timeInSeconds target:self selector:@selector(updateText) userInfo:nil repeats: YES/NO]; 

,並在你的更新方法,集最新的文本按照您的要求:

-(void) updateText { 
    self.timeRemainingLabel.text = latestTextForLabel; 
} 
+0

感謝您的幫助。我現在明白了:) – sri