Can't update text in UILabel
I have created my ViewController from UIViewController where add UILabel as; @property (nonatomic, retain) UILabel* progressLabel;
I initialize this label in 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:CGRectMak开发者_运维百科e(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];
}
And I have a method that must update label's text
-(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);
}
}
Why this code doesn't update progressLabel.text property? However in debuger console I see following text:
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
And when cycle is over I can see "9" in progress label?
The Run loop updates the UI. You might want to try calling the runloop in your for loop:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
Your method will all happen synchronously on the main thread, so you never give the label the chance to redraw until your whole method is over. You should consider an asynchronous pattern to update the label, so that your code allows the rest of the application's run loop a chance to work.
Try using an NSTimer
, and in the -timerDidFire:
update the label once appropriately.
The UI is updated in the application's main UI run loop. Not at the moment you set the text property. So as long as you are in your loop, the UI will not be updated. Once you exit the function, the UI will be updated.
A better idea would be to use NSTimer to execute a method every 1 second. Then your UI will be updated correctly.
精彩评论