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 Answer
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
- there is only one scene delegate.
- There is only one scene and one window.
- 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.shared?.window
it's cool only if you have only ONE scene which is not natural for scenes 🙂– imikeApr 5, 2020 at 14:43
self.view.window
.