在Xcode 12的SwiftUI项目中使用ViewRouter

问题描述

我尝试在新的Xcode 12项目中使用this方法(请参阅链接)作为创建SwiftUI应用程序登录页面的方法,但是我遇到了一个问题,即不知道要添加什么到主菜单中应用程序结构。我还是一个初学者,尝试将ContentView().environmentObject(ViewRouter())添加到主应用程序结构的WindowGroup中。我是完全错误的还是Xcode为什么不建立视图?有人可以帮忙吗? 在工作代码段下方:

import SwiftUI
import Foundation
import Combine

class SceneDelegate: UIResponder,UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: MotherView().environmentObject(ViewRouter()))
            self.window = window
            window.makeKeyAndVisible()
        }
    }
. . .
}

class ViewRouter: ObservableObject {
    let objectWillChange = PassthroughSubject<ViewRouter,Never>()
    var currentPage: String = "page1" {
        didSet {
            withAnimation() {
                objectWillChange.send(self)
            }
        }
    }
}

struct MotherView : View {
    @EnvironmentObject var viewRouter: ViewRouter
    var body: some View {
        VStack {
            if viewRouter.currentPage == "page1" {
                ContentViewA()
            } else if viewRouter.currentPage == "page2" {
                ContentViewB()
                    .transition(.scale)
            }
        }
    }
}

struct ContentViewA : View {
    @EnvironmentObject var viewRouter: ViewRouter
    var body: some View {
        Button(action: {self.viewRouter.currentPage = "page2"}) {
            Text("Login")
        }
    }
}

struct ContentViewB : View {
    
    @EnvironmentObject var viewRouter: ViewRouter
    
    var body: some View {
        Button(action: {self.viewRouter.currentPage = "page1"}) {
            Text("Logout")
        }
    }
}

现在,我想用Xcode 12样式替换SceneDelegate,但是以下方法不起作用。知道为什么吗?

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            MotherView().environmentObject(ViewRouter())
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)