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?
func textFieldDidEndEditing(UITextField) Tells the delegate when editing stops for the specified text field.
An object that displays an editable text area in your interface.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With