从AppDelegate获取ViewController中的值

时间:2019-08-14 15:32:21

标签: ios swift

我正在尝试从AppDelegate获取ViewController中的值,但无法这样做。

我只有一个ViewController。我试图将值设为常量或变量。它们都不起作用。

我不确定这是否正确,但是我尝试使用rootViewController进行访问。

class ViewController: UIViewController {
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    var test:String = "test"   
  // let test = "test" 
  }
}

在AppDelegate中

  func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let viewController = self.window?.rootViewController as? ViewController
    print("from_viewC \(String(describing: viewController?.test)))")
}

3 个答案:

答案 0 :(得分:1)

您必须在viewWillAppear外部声明变量,以使其可以从外部访问:

class ViewController: UIViewController {

  var test = "test"

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // whatever is in here...
  }

}

答案 1 :(得分:0)

像这样设置Windows根视图控制器:

self.window.rootViewController = ViewController()

和上面一样,您无法访问自己的价值。同样,在编译之前,必须使测试变量成为类成员。

答案 2 :(得分:0)

您为什么尝试在didFinishLaunchingWithOptions中访问rootViewController的变量?您的确切要求是什么?

DidFinishLaunchingWithOptions是分配rootViewController的地方!

您可以在appDelegate中的didEnterBackground,didEnterForeground,didBecomeActive委托函数中进行尝试,以访问rootViewController的变量!