Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift/iOS13 - Access SceneDelegate window variable in a ViewController

Tags:

ios

swift

ios13

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

like image 299
kironet Avatar asked Oct 24 '19 19:10

kironet


People also ask

How do I get SceneDelegate in Swift?

If you want the scene delegate for a specific view controller then note the following. From a UIViewController you can get its window from its view. From the window you can get its scene and of course from the scene you can get its delegate. However, there are plenty of times where a view controller has no window.

What is Rootviewcontroller in Swift?

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller's view as the content view of the window.

How do I get Windows on Swiftui?

To actually present a new window, we'll need to add another WindowGroup scene to the app's body property. The new scene will indicate that it expects to receive a value of type Note.ID . We'll also make sure, that the main scene and the detail scene get passed the shared data store as an environment object.


1 Answers

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
like image 79
Mojtaba Hosseini Avatar answered Sep 17 '22 10:09

Mojtaba Hosseini