Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

ios - Update a label through button from different view

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...