简体   繁体   中英

Can't set UILabel Text Programmatically

In my iOS app, I'm trying to set the text of a UILabel in another view.

I do this by passing a NSNotification to the viewController when it should be updated. I know it is receiving the message correctly because I log the message, but it just isn't appearing in the UILabel (which I added in the storyboard).

This is my code:

ProcessingViewController.h

@property (weak, nonatomic) IBOutlet UILabel *progressMessage;

ProcessingViewController.m

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgressDialog:) name:@"uploadProgress" object:nil];
}

-(void) updateProgressDialog: (NSNotification *) notification{
    NSString *message = [notification object];
    NSLog(@"received updateProgressDialog message of %@", message);
    self.progressMessage.text = message;
    [self.progressMessage setNeedsDisplay];
}

My storyboard:

在此处输入图片说明

Diagnosing this offline, we confirmed that this was really being received on a background thread. In that case, you can either post the notification to the main queue, or you can have updateProgressDialog dispatch the UI updates to the main queue:

-(void) updateProgressDialog: (NSNotification *) notification{
    NSString *message = [notification object];
    NSLog(@"received updateProgressDialog message of %@", message);
    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressMessage.text = message;
    });
}

I'm sorry but i don't really understand your question:

What i have in mind is you have to viewController and your passing a message from the childViewController to the parentViewController using NSNotificationCenter ? Is that cor

 - (void)viewDidLoad 
 {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgressDialog:) name:@"uploadProgress" object:nil];
 }

but if you want to send the message back the message using NSNotificationCenter

//childViewController.m

 //i tried adding this to your code to test if the `NSNotificationCenter ` responds, and it is responding
[[NSNotificationCenter defaultCenter] postNotificationName:@"uploadProgress" object:@"Your message"];

while i think what you need to do is to make sure the your update is at the main tread..

-(void) updateProgressDialog: (NSNotification *) notification{

    NSString *message = [notification object];

    NSLog(@"received updateProgressDialog message of %@", message);

    dispatch_async(dispatch_get_main_queue(), ^(void){
        self.progressMessage.text = message;
    });
}

Edit

and there you go, i got a down vote for having a slow internet while editing my answer..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM