简体   繁体   中英

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?

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;
}

Check and see if " VCT.textField " is not nil at that point. I suspect that you'll find it is nil.

You either need to expose it via " @property (strong) IBOutlet UITextField * textField " or you need to store the string somewhere else (eg a " NSString " property?) which then loads the text field when the view is fully loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM