作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
如何在 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/
我是一名优秀的程序员,十分优秀!