2010-02-26 57 views
3

我从UIViewController创建了我的ViewController,其中添加了UILabel as; @property(nonatomic,retain)UILabel * progressLabel;无法更新UILabel中的文本

我初始化的loadView

- (void)loadView { 

// Set main view to View Controller 
UIView* localView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] ]; 
self.view = localView; 
[localView release]; 

// Set progress label 
self.progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 420, 320, 20) ]; 
[self.progressLabel setFont:[UIFont fontWithName:@"Georgia" size:12]]; 
[self.progressLabel setTextColor:[UIColor whiteColor]]; 
[self.progressLabel setBackgroundColor:[UIColor blackColor]]; 
[self.view addSubview:self.progressLabel]; 

} 

这个标签,我必须更新标签的文本

-(void) doSomethig { 
for(int i = 0; i < 10; i++) { 
    NSString* str = [NSString stringWithFormat:@"%d", i]; 
    [self.progressLabel setText:str]; 
    [self.progressLabel.superview setNeedsDisplay]; 
    NSLog(@"%@", self.progressLabel.text); 
    sleep(1); 
} 
} 

为什么这个代码不更新progressLabel.text性能的方法?然而在debuger控制台我看到下面的文本:

2010-02-26 14:21:55.707 iLabelUpdate[6272:207] 0 
2010-02-26 14:21:56.708 iLabelUpdate[6272:207] 1 
2010-02-26 14:21:57.708 iLabelUpdate[6272:207] 2 
2010-02-26 14:21:58.709 iLabelUpdate[6272:207] 3 
2010-02-26 14:21:59.709 iLabelUpdate[6272:207] 4 
2010-02-26 14:22:00.710 iLabelUpdate[6272:207] 5 
2010-02-26 14:22:01.710 iLabelUpdate[6272:207] 6 
2010-02-26 14:22:02.711 iLabelUpdate[6272:207] 7 
2010-02-26 14:22:03.711 iLabelUpdate[6272:207] 8 
2010-02-26 14:22:04.711 iLabelUpdate[6272:207] 9 

当循环结束时,我可以看到“9”正在进行标签?

回答

1

UI在应用程序的主UI运行循环中更新。目前不设置文本属性。所以只要你在你的循环中,UI将不会被更新。一旦你退出该功能,UI将被更新。

一个更好的主意是使用NSTimer每1秒执行一次方法。然后你的用户界面将被正确更新。

2

你的方法将在主线程中同步发生,所以你永远不会让标签有机会重绘,直到你的整个方法结束。您应该考虑使用异步模式更新标签,以便您的代码允许应用程序运行循环的其余部分有机会工作。

尝试使用NSTimer,并在-timerDidFire:更新标签一次适当。

3

运行循环更新UI。您可能想尝试在for循环中调用runloop:

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];