Swift/iOS13-在ViewController中访问SceneDelegate窗口变量 [英] Swift/iOS13 - Access SceneDelegate window variable in a ViewController

查看:341
本文介绍了Swift/iOS13-在ViewController中访问SceneDelegate窗口变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从ViewController中的SceneDelegate访问窗口变量?基本上,我需要该UIApplication.shared.delegate.window的替代方法,但找不到任何东西

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

推荐答案

已更新

iOS 13 中,应用程序可以具有多个活动窗口,因此您需要访问所需的窗口.因此,您可以像这样访问任何View的窗口:

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

如果您真的要访问UISceneDelegate,则可以按以下方式访问它:

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

self.view.window.windowScene.delegate

旧:不推荐:

假设

  1. 只有一个场景代表.
  2. 只有一个场景和一个窗口.
  3. 应用程序中的所有视图控制器都是该场景及其窗口的一部分.

您可以像这样在SceneDelegate中实现一个辅助变量:

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

这篇关于Swift/iOS13-在ViewController中访问SceneDelegate窗口变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆