如何从另一个 ViewController (Swift) 访问 UITextField 中的文本? [英] How do I access text in UITextField from another ViewController (Swift)?

查看:24
本文介绍了如何从另一个 ViewController (Swift) 访问 UITextField 中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个 ViewController 上有一个 UITextField,我希望能够在第二个 ViewController 上有一个标签 = 无论用户输入什么.

I have a UITextField on one ViewController and I want to be able to have a Label on the second ViewController = whatever the user enters.

但是,我在尝试执行此操作时遇到错误.我知道 Swift 不使用导入,所以我不知道该怎么做.

However, I get an error when trying to do this. I know Swift doesn't use import so I'm not sure what to do.

// First View Controller

 @IBOutlet weak var textOne: UITextField!

// Second View Controller

    @IBOutlet weak var theResult: UILabel!

theResult.text = textOne.text

错误:未解析的标识符

推荐答案

看起来您实际上只想访问 UITextField 中的文本,而不是字段本身.因此,您应该使用 prepareForSegue 将文本从第一个 ViewController 发送到第二个 ViewController.

It looks like that you in reality want to just access the text from the UITextField and not the field itself. So you should send the text to the second ViewController from your first one by using prepareForSegue.

但在此之前,您必须设置 segue 的名称,以便 Swift 知道要发送哪些数据:

But before, you have to set the name of your segue so that Swift knows which data to send:

如您所见,我们将 segue 命名为 segueTest.

As you see, we name the segue segueTest.

所以现在我们可以在 FirstViewController 中实现 prepareForSegue 方法并设置应该发送到第二个的数据.

So now we can implement the prepareForSegue-method in the FirstViewController and set the data which should be sent to the second.

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
        var svc = segue!.destinationViewController as secondViewController;

        svc.theText = yourTextField.text

    }
}

要做到这一点,当然必须在 SecondViewController 中设置一个变量:

That you can do that, you have to set a variable in your SecondViewController of course:

var theText:String!

这篇关于如何从另一个 ViewController (Swift) 访问 UITextField 中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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