gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:09:52 25 4
gpt4 key购买 nike

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

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

我的 View Controller 2:

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

}

View Controller :

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)名称。

关于ios - 如何在 Swift 的另一个类中设置变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27950446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com