SwiftUI 返回到 SceneWillEnterForeground SceneDelegate.swift 中的 RootView [英] SwiftUI go back to RootView in sceneWillEnterForeground SceneDelegate.swift

查看:27
本文介绍了SwiftUI 返回到 SceneWillEnterForeground SceneDelegate.swift 中的 RootView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果应用程序将进入前台,我们尝试将当前视图重置为 Root.

we try to reset the current View to Root if App will enter Foreground.

我们如何在 SwiftUI 中做到这一点?

How can we do that in SwiftUI?

func sceneWillEnterForeground(_ scene: UIScene) {
      let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let contentView = RootView().environment(\.managedObjectContext, context)
    if let windowScene = scene as? UIWindowScene {
        let singleOrder = SingleOrder()
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView.environmentObject(singleOrder))
        self.window = window
        window.makeKeyAndVisible()
    }
}

推荐答案

没有返回",但可能的方法是重新创建根视图控制器,通过将默认"生成的内容创建移动到其他委托方法中,如下所示...

There is no "go back" but the possible approach is to recreate root view controller, by moving "by default" generated content creation into other delegate method as below...

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        self.window = window
    }
}


func sceneWillEnterForeground(_ scene: UIScene) {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let contentView = RootView().environment(\.managedObjectContext, context)
    let singleOrder = SingleOrder()
    window?.rootViewController = UIHostingController(rootView: contentView.environmentObject(singleOrder))
    window?.makeKeyAndVisible()
}

这篇关于SwiftUI 返回到 SceneWillEnterForeground SceneDelegate.swift 中的 RootView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆