0

我尝试在新的 Xcode 12 项目中使用方法(请参阅附加链接)作为为 SwiftUI 应用程序创建登录页面的一种方式,但我遇到了不知道要添加到主 App 结构中的内容的问题。我仍然是初学者,并尝试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())
        }
    }
}
4

1 回答 1

0

请尝试以下步骤:

  1. 删除整个 SceneDelegate 类(在你的情况下不需要 SceneDelegate 类)

  2. 修改您的 ViewRouter 类,如:

    类 ViewRouter: ObservableObject { @Published var currentPage: String = "page1" }

于 2020-09-25T02:07:17.950 回答