Search code examples
iosobjective-cuiviewcontrolleruistoryboarddata-sharing

Update UITextField from a different ViewController iOS


I have a text field in my master view controller.. And I am using FPPopover to display another view controller on top of my master view controller.. I wanna get the name of the user from FPPopoverController and put in a text field in my master view controller. I tried the followings but didnt work..

 MasterViewController *vc = [[MasterViewController alloc] init];
  vc.nameTextField.text = self.nameField.text;


    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
    MasterViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"MasterViewController"];

    vc.nameTextField.text = self.nameField.text;

What else can I try? Thanks.


Solution

  • Delegation is the best method I think but the easiest way is using notifications.

    MyPopoverViewController implementation

    - (void)doneButtonPressed:(id)sender{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"notification"
                                                            object:self
                                                          userInfo:@{@"aKey":self.textfield.text} ];
    }
    

    In your master view controller viewdidload method

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

    and lastly add this method..

    - (void)updateTextField:(NSNotification *)notification {
         self.nameTextField.text = [notification.userInfo objectForKey:@"aKey"];
    }