我在 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)
Run Code Online (Sandbox Code Playgroud)
当然,这现在不起作用,因为 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
}
Run Code Online (Sandbox Code Playgroud)
自定义类.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)
Run Code Online (Sandbox Code Playgroud)
可能不推荐如此处所述: https: //stackoverflow.com/a/58547992/9511942,但它有效
编辑2:这是我的另一个解决方案,感谢/sf/answers/4099034411/
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
Run Code Online (Sandbox Code Playgroud)
如果有人找到更好的解决方案,请分享。
小智 2
使用该UIApplication.shared.windows属性获取应用程序窗口。请参考https://developer.apple.com/documentation/uikit/uiapplication/1623104-windows
| 归档时间: |
|
| 查看次数: |
7444 次 |
| 最近记录: |