我在Xcode11中创建了一个新的故事板项目,并试图从自定义类中呈现一个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'类型的值没有'member window'
如何使这段代码现在能够工作?
我想做什么:
当用户点击推送通知托盘时,我想展示一个视图控制器。
编辑:目前,我通过在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://dev59.com/0lMH5IYBdhLWcg3wuxw-#58547992,但它可以工作。
编辑2:这是我的另一个解决方案,感谢https://dev59.com/Z7fna4cB1Zd3GeqPmx0l#58557634
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
如果有人找到更好的解决方案,请分享。
var window: UIWindow?
。 - Prashant Tukadiyawindow!
,我会得到“致命错误:意外地发现nil值”。 - kironet