我想从AppDelegate获取ViewController变量,我尝试过:
//1.
print(ViewController().strName)
//2.
let vc = ViewController()
print(vc.strName)
//3.
let vc = UIApplication.shared.keyWindow!.rootViewController as! ViewController
print(vc.strName)
全部不起作用,打印值为空...
ViewController中的代码:
var strName : String = ""
override func viewDidLoad() {
strName = "Tom"
}
答案 0 :(得分:0)
我建议在此链接Swift: How to access in AppDelegate variable from the View controller?中进行检查 否则请尝试在视图控制器中
class ViewController: UIViewController {
var strName = "someString" // some value
}
在AppDelegate中,
var mainViewController = ViewController()
func applicationWillEnterForeground(_ application: UIApplication) {
_ = self.window?.rootViewController as? ViewController
print(mainViewController.strName)
}
答案 1 :(得分:0)