变量共享

时间:2015-02-19 02:12:03

标签: variables swift viewcontroller sharing

我有一个应用程序,当在原始视图上按下按钮时,会弹出另一个视图。基本上,我希望能够从原始视图中的文本字段中获取文本,并将其粘贴到新视图中的标签上。我已经看到了一堆Obj-c的答案,但没有快速的答案。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用prepareForSegue将数据从一个视图传递到另一个视图。 这是代码:

<强> ViewController.swift

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var txt: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "goNext" {
        let nextView :nextViewController = segue.destinationViewController as nextViewController

        nextView.passedData = self.txt.text

        }
    }
}

<强> nextViewController.swift

import UIKit

class nextViewController: UIViewController {

@IBOutlet weak var lbl: UILabel!
var passedData = String()
override func viewDidLoad() {
    super.viewDidLoad()

    self.lbl.text = self.passedData
    }
}

在这里,我为您创建了一个示例项目,以供更多参考:https://github.com/DharmeshKheni/pass-Data-with-prepareForSegue-in-swift