如何在主App结构中初始化EnviromentObject?

时间:2020-10-01 17:02:26

标签: swift swiftui

我想像这样在EnviromentObject结构中初始化App

class SceneOnDisplay: ObservableObject {
    @Published var scene = 0
}

@main
struct MyApp: App {
    @EnvironmentObject var sceneOnDisplay: SceneOnDisplay
    
    var body: some Scene {
        WindowGroup {
            switch sceneOnDisplay.scene{
            case 1:
                PractiseSceneView()
            default:
                ContentView()
            }
        }
    }
}

但是因为这是根场景/视图,并且没有SceneDelegate,所以我没有地方可以初始化EnviromentObject。因此,我收到此错误:

线程1:致命错误:找不到SceneOnDisplay类型的ObservableObject。作为此视图的祖先,可能没有用于SceneOnDisplay的View.environmentObject(_:)。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以创建专门用于路由的顶级视图:

@main
struct MyApp: App {
    @StateObject var sceneOnDisplay = SceneOnDisplay() // init here

    var body: some Scene {
        WindowGroup {
            RoutingView()
                .environmentObject(sceneOnDisplay) // and pass as an `EnvironmentObject`
        }
    }
}

struct RoutingView: View {
    @EnvironmentObject var sceneOnDisplay: SceneOnDisplay

    var body: some View {
        switch sceneOnDisplay.scene {
        case 1:
            PractiseSceneView()
        default:
            ContentView()
        }
    }
}