Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UITextField text property in prepareForSegue

I have a textField in my ViewController1. I have a push segue to my ViewController2 which also has a textField. I need to set the textField.text in my ViewController2 to be equal to the text in the textField in my ViewController1. Here's the code I have:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqual:@"ViewController2"])
    {
        ViewController2 *VCT = [segue destinationViewController];
        VCT.title = @"View Controller #2";
        VCT.textField.text = self.textField.text;
    }
}

The title setter works just fine. Why is the textField not working?

like image 228
Cody Winton Avatar asked Aug 08 '13 22:08

Cody Winton


People also ask

What is UITextField for?

func textFieldDidEndEditing(UITextField) Tells the delegate when editing stops for the specified text field.

What is UITextField in Swift?

An object that displays an editable text area in your interface.


1 Answers

You cannot set the text of the UITextField (and any other components like UILabel and UITextView) in the prepare for segue, because all view components of the recently allocated controller are not initialized yet (at this time, they are all nil), they only will be when the viewController is presented (and it's view loaded).

You have to create a NSString property in the presented viewController, and then, somewhere inside your another view controller, like viewDidLoad, set the text of the textField as this property value.

Like this:

In the viewController that will present the another viewController:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"ViewController2"])
    {
        ViewController2 *vc2 = [segue destinationViewController];
        vc2.myString = self.textField.text;
    }
}

And inside the presented viewController:

- (void)viewDidLoad
{
    [super viewDidLoad];

    (...)
    self.textField.text = self.myString;
}
like image 68
Lucas Eduardo Avatar answered Nov 03 '22 06:11

Lucas Eduardo