Update a label through button from different view

2019-01-15 22:34发布

问题:

How to update a label by button clicks when they both are in different classes of uiview controller...when button is clicked,the label should be update...i tried many times..but its not happening..

one more Question is my app is running good in simulator but when i run on device the dynamically created button(button image) is not visible,action is performing but image is missing..may i know why?

回答1:

There are a few ways to maintain communication between views (view controllers, actually) in iOS. Easiest of which for me is sending notifications. You add an observer for a notification in the view you want to make the change, and from the view that will trigger the change, you post the notification. This way you tell from ViewController B to ViewController A that "something is ready, make the change"

This, of course, requires your receiver view to be created and already be listening for the notification.

In ViewController B (sender)

- (void)yourButtonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
}

In ViewController A (receiver) Add the observer to listen for the notification:

- (void)viewDidLoad
{
    //.........
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(makeTheChange) name:@"theChange" object:nil];
}

Do NOT forget to remove it (in this case, on dealloc)

- (void)dealloc
{
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"theChange" object:nil];
     [super dealloc];
}

And finally, the method that will update your label

- (void)makeTheChange
{
    yourLabel.text = @"your new text";
}


回答2:

Not sure if it's a good solution, but you could store the text in a global NSString when clicking on the button, then put that string into your label when loading the second view.