如何从Swift中的容器视图获取属性值 [英] How do I get the property value from a container view in Swift

查看:78
本文介绍了如何从Swift中的容器视图获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1个UIViewController,其中包含一个UIContainerView和一个UIButton. 另外,我有一个UITableViewController(它有一个UITextField和一个UITextView),它嵌入在UIViewController的UIContainerView中.

I have 1 UIViewController that contains a UIContainerView and a UIButton. Also, I have a UITableViewController (It has a UITextField and a UITextView) that is embedded in the UIContainerView in the UIViewController.

我正在尝试获取将在TextField和TextView中使用的字符串值.

I'm trying to get the string values that will be available in TextField and in TextView.

我尝试使用segue来获取属性值,但是我没有这样做,请参见下面的代码.

I tried to use the segue to get the properties values, but I failed to do so, see the code below.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "TVCSegue" {
        let containerTVC = segue.destination as? FieldsTVC
        self.textField.text = FieldsTVC?.textField?.text
        self.textView.text = FieldsTVC?.textView?.text
    }
}

上面的代码在UIViewController中具有'textField'和'textView'作为属性,以将值分配给它们.

The code above has 'textField' and 'textView' as properties in the UIViewController to assign the values to.

但是我相信这是行不通的,因为我在它们改变之前就获得了价值.请为我提供一种实用的方法.

But I believe that it doesn't work as I get the values before they changes. Please provide me with a functional way to do so.

推荐答案

在加载主视图时,容器对为其分配的初始/根ViewController执行segue.在这一点上,您可以获得对它的引用:

When your main view loads, the container performs a segue to its assigned initial / root ViewController. At that point, you can get a reference to it:

var theFieldsTVC: FieldsTVC?

现在,在准备segue时,分配该变量:

Now, in prepare for segue, assign that variable:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "TVCSegue" {

        if let vc = segue.destination as? FieldsTVC {
            theFieldsTVC = vc
        }

    }
}       

然后,您可以:

@IBAction func buttonTapped(_ sender: Any) {

    self.textField.text = theFieldsTVC?.textField?.text
    self.textView.text = theFieldsTVC?.textView?.text

}

这篇关于如何从Swift中的容器视图获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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