【问题标题】:SwiftUI go back to RootView in sceneWillEnterForeground SceneDelegate.swiftSwiftUI 回到sceneWillEnterForeground SceneDelegate.swift 中的RootView
【发布时间】:2020-01-07 02:08:00
【问题描述】:

如果 App 进入前台,我们会尝试将当前 View 重置为 Root。

我们如何在 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()
    }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

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

    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()
    }
    

    【讨论】:

    • 但是如果我们重新创建视图。另一种观点发生了什么?加载两次?
    • 其他视图?代码应该“移动”,而不是“复制”。
    • 我将代码移到了这一部分,但每次应用程序进入前台时都会复制视图。
    • 我认为我们需要删除旧场景或视图。
    • moment...它重新创建了窗口...我马上更新
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2021-12-02
    • 2017-05-12
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多