Xcode - update ViewController label text from different view

后端 未结 4 1940
予麋鹿
予麋鹿 2020-12-01 21:54

I have two view Controllers in my project ViewController, SettingsView. Here I am trying to update the ViewController\'s label, when i

相关标签:
4条回答
  • 2020-12-01 22:31

    You have to implement protocols for that. Follow this:

    1) In SettingView.h define protocol like this

     @protocol ViewControllerDelegate
    
     -(void) updateLabel;
    
      @end
    

    2) Define property in .h class and synthesis in .m class..

        @property (nonatomic, retain) id <ViewControllerDelegate> viewControllerDelegate;
    

    3) In SettingsView.m IBAction

      -(IBAction)backToMain:(id) sender 
     {
         [viewControllerDelegate updateLabel];
     }
    

    4) In ViewController.h adopt protocol like this

    @interface ViewController<ViewControllerDelegate>
    

    5) In viewController.m include this line in viewDidLoad

    settingView.viewControllerDelegate=self
    
    0 讨论(0)
  • 2020-12-01 22:32

    You are not exactly calling the correct vc. This is because you are creating a new instance of that class and calling the updateLabel of that instance.

    You have a few options.

    1. Either implement it as a delegate callBack (delegate messagePassing, or delegate notification - however you want to call it) to notify that class instance to call the updateLabel method.

    2. Use the original instance VC as a dependency injection into the class that you are on right now, and use that instance to call the updateLabel

    3. Use NSNotifications / NSUserDefaults to communicate between viewControllers and setup a notification system for your actions. This is quite easy, but not really great in the long run.

    I would RECOMMEND option 1 (or) option 2.

    0 讨论(0)
  • 2020-12-01 22:49

    Your label is not updating because , you are trying to call updateLabel method with a new instance.

    You should call updateLabel of the original instance of viewcontroller from which you have presented your modal view.

    you can use a delegate mechansim or NSNotification to do the same.

    Delegate mechnaism would be clean. NSNotification is quick and dirty.

    0 讨论(0)
  • 2020-12-01 22:52

    Simply declare like this in SettingsView class:

     UILabel *lblInSettings;// and synthesize it
    

    Now assign like below when you presenting Settings viewController:

    settingsVC.lblInSettings=self.myLabel;
    

    Then whatever you update in lblInSettings it will be present in MainView obviously.... no need for any delegate methods or updating methods.

    Means if you assign at the time of dismissing like
    lblInSettings.text=@"My new value";
    then self.myLabel also will be updated.
    

    Let me know if you have any queries?

    0 讨论(0)
提交回复
热议问题