Search code examples
iphoneiosuiviewcontrolleruilabeltransfer

Putting text input from one view to another


I have tried so many tutorials that I am wondering why I am not getting such a simple problem. I have a view controller called SetBudgetViewController. I have a text field in this view that I have connected as an outlet called *amountToSpend. I have another view used elsewhere in the app that has a label called *amountSet. How do I make the numbers entered into the first text field be displayed in the label in the other view? Thank you all so much (this is driving me mad)!


Solution

  • First, declare a property in the other view controller:

    @property (strong, nonatomic) NSString *amountToSpend;
    

    In SetBudgetViewController, in your -(void)prepareForSegue method:

    if([segue.identifier isEqualToString:@"YourIdentifier"])
    {
        OtherViewController *vc = segue.destinationViewController;
        vc.amountToSpend = self.amountToSpend.text;
    }
    

    In the other view controller, display the amount in viewDidLoad.

    self.amountSet.text = self.amountToSpend;
    

    EDIT 2: Alternative for passing data between VCs not close to each other. You can repeat the action above or use NSUserDefaults.

    In SetBudgetViewController after amount is entered:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.amountToSpend.text forKey:@"AmountToSpend"];
    [defaults synchronize];
    

    In the other view controller, display the amount in viewDidLoad.

    self.amountSet.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"AmountToSpend"];