在prepareForSegue中设置UITextField文本属性 [英] Set UITextField text property in prepareForSegue

查看:98
本文介绍了在prepareForSegue中设置UITextField文本属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ViewController1中有一个textField。我有一个push segue到我的ViewController2,它也有一个textField。我需要将ViewController2中的textField.text设置为等于ViewController1中textField中的文本。这是我的代码:

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

标题设置工作正常。为什么textField无效?

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

推荐答案

您无法设置 UITextField的文本(以及 UILabel UITextView 等任何其他组件),因为所有视图组件都是最近分配的控制器尚未初始化(此时,它们都是 nil ),它们仅在呈现viewController时(并且它的视图已加载)。

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).

你必须在呈现的viewController中创建一个 NSString 属性,然后在另一个视图控制器内的某个地方,比如 viewDidLoad ,将textField的文本设置为此属性值。

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.

像这样:

在将呈现另一个viewController的viewController中:

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

在显示的viewController中:

And inside the presented viewController:

- (void)viewDidLoad
{
    [super viewDidLoad];

    (...)
    self.textField.text = self.myString;
}

这篇关于在prepareForSegue中设置UITextField文本属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆