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

t0r*_*199 1 variables class uiviewcontroller ios swift

如何在swift中的myClass2另一个类myClass中为类中的变量添加值?

我已经尝试了类似的东西myClass2().myvariable = "value",但这没有用; 我的变量值仍然是nil.这是代码:

myViewController2:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

视图控制器:

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";
    }

}
Run Code Online (Sandbox Code Playgroud)

rde*_*mar 5

您正在创建一个名为myClass实例的myViewController2实例,但这不是您推入堆栈的实例 - 正在推送的实例是view2.所以toView2Pressed的最后一行应该是,

view2.myVariable = "my new value"
Run Code Online (Sandbox Code Playgroud)

你应该删除该行,让myClassInstance = myViewController2().它没有任何意义.您还应该用大写字母开始您的班级名称.