UILabel text not being updated

老子叫甜甜 提交于 2019-11-28 04:07:26

You may be facing an issue with threading as mentioned in the comments above. If you have a method that runs on the main thread and does some activity (such as search a database), updates that you make to the UI will not be committed until the run loop gets control. So, if you have a long, time consuming task going on on the main thread, run this code after setting the text of the label:

- (void)doSomethingTimeConsuming
    ... consume some time ...
    ... set text of label ...
    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
    ... continue long operation ...
}

This should flush out any UI changes that you have made. Although this may be a sensible and functional hack, it doesn't beat the alternative. I highly suggest that you perform your app's time consuming tasks on a background thread, and update the UI through the main thread using performSelectorOnMainThread:withObject:waitUntilDone:. See Apple's page on iOS Thread Management.

In my case the function that was updating was called from a touch recognizer on a thread, but the place in the function where I'm changing the value of the label's text property I put it back on the main thread:

dispatch_async(dispatch_get_main_queue(), ^{
    [self.someLabel setText:someString];
});

Mine's a bit more unexpected, though reasonable--just not something anyone thinks too hard about.

I'm supposed to update the UILabel when I receive an NSNotification that I fired somewhere else. However, the notification was fired from a background thread so even the listener methods that update the label's text are fired in the background.

If you're relying on an NSNotification to update the label, or any of your views, do fire the NSNotification from the main UI thread.

I had a UILabel showing a level number that would not update to the new level number on a UIViewController. The only viable solution I could find that worked was to call setNeedsDisplay on the main thread of the view controller that owned the UILabel

-(void)changeLevelLabel:(int)theLevel {
dispatch_async(dispatch_get_main_queue(), ^{
    self.levelLabel.text = [NSString stringWithFormat:@"%d",theLevel];
    [self.levelLabel setNeedsDisplay];
});

}

See http://iosdevelopmentjournal.com/blog/2013/01/16/forcing-things-to-run-on-the-main-thread/ for a more detailed explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!