我可以访问标签或文本字段的文本而无需在swift 3.0中创建插座吗?

时间:2017-03-16 06:17:17

标签: swift

我是快速开发的新手。我试图在不创建插座的情况下访问标签文本。我将标签设置为标签并尝试获取文本。

我提到了这个链接 How Can I access the textfields in static TableViewcells without creating referencing outlet?

我成功了,但我想以编程方式将该文本导航到下一个ViewController,但无法做到这一点。任何人都可以帮助我。

我尝试了以下代码

for view: UIView in self.view.subviews {
        if (view is UILabel)  {
            let stortboard = UIStoryboard.init(name:"Main",bundle:nil)
            let vc =  stortboard.instantiateViewController(withIdentifier:  "SecondViewControllerID") as? SecondViewController

            let lbl: UILabel? = (view as? UILabel)

            vc?.lblData = lbl?.text
            print(lbl?.text ?? "not found")
            //self.navigationController?.pushViewController(vc!, animated: true)
            self.present(vc!, animated: true, completion: nil)
        }
}

2 个答案:

答案 0 :(得分:2)

如果要查找标记,则可以按照描述使用viewWithTag。

设置文本字段的标记如下:

enter image description here

//Get One By One with Tag
if let txtField1 = self.view.viewWithTag(1) as? UITextField {
    print(txtField1.text!)
}

希望对你有所帮助。

答案 1 :(得分:1)

我尝试了你的代码并且它有效。确保lblData:String!

中有SecondViewController

试试这个

    for view in self.view.subviews {
        if (view is UILabel)  {
            let stortboard = UIStoryboard.init(name:"Main",bundle:nil)
            let vc =  stortboard.instantiateViewController(withIdentifier:  "SecondViewControllerID") as? SecondViewController
            let lbl: UILabel? = (view as? UILabel)
            vc?.lblData = lbl?.text
            print(lbl?.text ?? "not found")
            self.present(vc!, animated: true, completion: nil)
        }
    }