Update a label through button from different view

后端 未结 2 1262
离开以前
离开以前 2020-12-07 04:56

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.

相关标签:
2条回答
  • 2020-12-07 05:21

    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.

    0 讨论(0)
  • 2020-12-07 05:23

    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";
    }
    
    0 讨论(0)
提交回复
热议问题