如何在 Swift 中的另一个 class 中设置变量值

How to set a variable value in another class in Swift

如何从 swift 中的另一个 class myClass 向 class myClass2 中的变量添加值?

我已经尝试过 myClass2().myvariable = "value" 之类的方法,但这没有用;我的变量值仍然是 nil。这是代码:

我的ViewController2:

import UIKit

class MyViewController2: UIViewController {

    var myVariable : String?;

    @IBOutlet weak var display: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

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

    @IBAction func showPressed(sender: AnyObject) {
        display.text = myVariable;
    }

}

ViewController:

import UIKit

class ViewController: UIViewController {

    let myClassInstance = myViewController2();
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    @IBAction func toView2Pressed(sender: AnyObject) {

        let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as myViewController2;
        self.navigationController?.pushViewController(view2, animated: true);
        myClassInstance.myVariable = "my new value";
    }

}

您正在创建一个名为 myClass 实例的 myViewController2 实例,但这不是您压入堆栈的实例——被压入的实例是 view2。所以 toView2Pressed 的最后一行应该是

view2.myVariable = "my new value"

您应该删除该行,let myClassInstance = myViewController2()。它毫无用处。您的 class 名字也应该以大写字母开头。