Swift/iOS13 - Access SceneDelegate window variable in a ViewController

不打扰是莪最后的温柔 提交于 2019-12-01 06:34:35

问题


Is it possible to access window variable from SceneDelegate in a ViewController? Basically I need an alternative for this UIApplication.shared.delegate.window but can't find anything


回答1:


Updated

From iOS 13, apps can have multiple active windows, so you need to access the window you want. So you can access a window of any View like this:

self.view.window

if you really want to access the UISceneDelegate you can access it like:

self.view.window.windowScene.delegate

Old: and NOT recommended:

Assuming

  1. there is only one scene delegate.
  2. There is only one scene and one window.
  3. All view controllers in the app are all part of that one scene and its window.

You can implement a helper variable in SceneDelegate like this:

private(set) static var shared: SceneDelegate?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    guard let _ = (scene as? UIWindowScene) else { return }
    Self.shared = self
}

then you can access it anywhere like this:

SceneDelegate.shared?.window // or anything else



回答2:


sceneDelegate = self.view.window?.windowScene?.delegate as! SceneDelegate`



来源:https://stackoverflow.com/questions/58547907/swift-ios13-access-scenedelegate-window-variable-in-a-viewcontroller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!