user1626438
user1626438

Reputation: 133

Updating uilabel in view controller underneath another

I have two view controllers, FirstViewController and FourthViewController. FirstViewController is my initial view controller. I present FourthViewController with

UIViewController *fourthController = [self.storyboard instantiateViewControllerWithID:@"Fourth"];
[self presentViewController:fourthController animated:YES completion:nil];

Then, in FourthViewController's .m I'd like to change the text of a UILabel in FirstViewController. So I use

UIViewController *firstController = [self.storyboard instantiateViewControllerWithID:@"First"];
firstController.mainLab.text = [NSMutableString stringWithFormat:@"New Text"];

However, after I use

[self dismissViewControllerAnimated:YES completion:nil];

I find that my mainLab's text has not updated. Does anyone know why?

Upvotes: 2

Views: 642

Answers (2)

GSD
GSD

Reputation: 436

If you want to update the label on first screen and nothing else then go for notifications. It's better rather you write the delegate. Because you want to update only label text thats it.

Upvotes: 0

Krishnabhadra
Krishnabhadra

Reputation: 34265

When you are calling this line from FourthViewController.m you are actually creating a new instance of FirstViewController, rather than using the already created one.

UIViewController *firstController = [self.storyboard 
                             instantiateViewControllerWithID:@"First"];

You can tackle this in two ways.

1) Using notification

post a notification from FourthViewController when label text need to be changed.

[[NSNotificationCenter defaultCenter] postNotificationName:@"updateLabel" 
        object:self];

In your FirstViewController viewDidLoad methodcreate an observer that waits for this notification to get fired.

[[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(updateLabelCalled:) 
        name:@"updateLabel"
        object:nil];

Implement updateLabelCalled: and update label.

- (void) updateLabelCalled:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"updateLabel"]){
        //write code to update label
    }

}

2) Implementing delegate

It is already explained here in stackoverflow. The basic idea is you create a FourthViewController delegate, and create a delegate method to updateLabel. FirstViewController should implement this method.

Upvotes: 3

Related Questions