ios - 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
如果有人找到更好的解决方案,请分享。
解决方案
使用该UIApplication.shared.windows
属性获取应用程序窗口。请参考https://developer.apple.com/documentation/uikit/uiapplication/1623104-windows
推荐阅读
- javascript - 与转义字符不匹配的负后视,在转义反斜杠上失败
- amazon-web-services - 如何在 AWS Sagemaker 笔记本实例中设置多个环境变量?
- json - 在 ARM 模板中的 if 语句中格式化包含单引号和双引号的 JSON
- sql - 插入 sql 行而不是删除的行会使数据库大小增加或仍然相同
- android - 图片不适合android react native
- sql - 如何计算每位员工每年的数据
- flutter - 如何在一台具有多个 Dart 和 webdev 版本的机器上运行 flutter_web 和 angulardart?
- java - 多次包含相同的布局(包含回收站视图)
- regex - TCL:每一行的正则表达式应该是什么样的?
- typescript - Worksheets.load("items") 失败,导致访问被拒绝错误