我在 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 中不再有 window 变量,它已被移至 SceneDelegate。
错误: “AppDelegate”类型的值没有成员“window”
您现在如何使这段代码工作?
我正在尝试做的事情:
我试图在用户点击/点击推送通知托盘时显示一个 ViewController。
编辑:现在我能够通过在 SceneDelegate 中创建一个私有(private)静态变量并在我的自定义类中访问该变量来使其工作:
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
关于ios - Swift/iOS13 - 来自自定义类的 UIApplication.shared.delegate.window?.rootViewController?.present(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58553822/