无法更新UILabel中的文本

时间:2010-02-26 12:24:49

标签: iphone cocoa cocoa-touch

我已经从UIViewController创建了我的ViewController,其中添加了UILabel; @property(非原子,保留)UILabel * progressLabel;

我在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”标签?

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

尝试使用NSTimer,并在-timerDidFire:中正确更新标签

答案 2 :(得分:1)

UI在应用程序的主UI运行循环中更新。目前还没有设置text属性。因此,只要您处于循环中,UI就不会更新。退出该功能后,UI将会更新。

更好的想法是使用NSTimer每1秒执行一次方法。然后您的UI将正确更新。