How get rootViewController with iPadOS multi window (SceneDelegate)?

谁说我不能喝 提交于 2019-12-03 16:01:35

Now you have more than one rootViewController, one for each scene. First, you have to answer which one you need at the moment of usage.

Probably you want to get one of the rootViewController of the currently active scene then you can use this:

        var rootVC:UIViewController? = nil
        if #available(iOS 13.0, *) {
            for scene in UIApplication.shared.connectedScenes {
                if scene.activationState == .foregroundActive {
                    rootVC = ((scene as? UIWindowScene)!.delegate as! UIWindowSceneDelegate).window!!.rootViewController
                    break
                }
            }
        } else {
            // Fallback on earlier versions
        }

You can access connected scenes trough the

UIApplication.shared.connectedScenes

As per Apple documentation

Connected scenes are those that are in memory and potentially doing active work. A connected scene may be in the foreground or background, and it may be onscreen or offscreen.

Then you can iterate through them and try to get UIWindowScene from there.

guard let windowScene = (scene as? UIWindowScene) else { return }

print(windowScene.windows) // this will print windows associated with the scene.

On the other hand, from the view controller you can access the window through the view:

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