首页 > 解决方案 > Swift/iOS13 - UIApplication.shared.delegate.window?.rootViewController?.present() 来自自定义类

问题描述

我在 Xcode11 中创建了一个新的Storyboard 项目,并尝试从这样的自定义类中呈现一个 ViewController (在旧项目中工作得很好):

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
appDelegate.window?.makeKeyAndVisible()
appDelegate.window?.rootViewController?.present(vc, animated: true, completion: nil)

当然现在这不起作用,因为 AppDelegate 中不再有窗口变量已移动到 SceneDelegate。

错误: Value of type 'AppDelegate' has no member 'window'

你现在如何使这段代码工作?

我正在尝试做的事情:

当用户点击/单击推送通知托盘时,我试图显示一个 ViewController。

编辑:现在我能够通过在 SceneDelegate 中创建一个私有静态变量并在我的自定义类中访问该变量来使其工作:

SceneDelegate.swift

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
}

CustomClass.swift

let sceneDeleage = SceneDelegate.shared
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
sceneDeleage?.window?.makeKeyAndVisible()
sceneDeleage?.window?.rootViewController?.present(vc, animated: true, completion: nil)

可能不建议如此处所述:https ://stackoverflow.com/a/58547992/9511942 ,但它有效

EDIT2:感谢https://stackoverflow.com/a/58557634/9511942 ,这是我的另一个解决方案

    let window = UIApplication.shared.windows.first
    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc : UIViewController = storyboard.instantiateViewController(withIdentifier: "NotificationVC") as UIViewController
    window?.makeKeyAndVisible()
    window?.rootViewController = vc

如果有人找到更好的解决方案,请分享。

标签: iosswiftios13

解决方案


使用该UIApplication.shared.windows属性获取应用程序窗口。请参考https://developer.apple.com/documentation/uikit/uiapplication/1623104-windows


推荐阅读