SwiftUI错误没有找到类型为GlobalEnvironment的ObservableObject

时间:2020-07-17 19:55:57

标签: ios swift swiftui

我以为我一切设置正确,但是我的应用程序崩溃了……在SceneDelegate中,我有以下代码:

// Create the SwiftUI view that provides the window contents.
        let contentView = CalculatorView().environmentObject(GlobalEnvironment())

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()

在我的CalculatorView结构中,我具有:

@EnvironmentObject var env: GlobalEnvironment

var body: some View {

                HStack() {
                    Spacer()
                    Text(env.outputToScreen)
                        

我有一个名为“ GlobalEnvironment”的类,它继承自ObservableObject,其@Published属性设置如下:

class GlobalEnvironment: ObservableObject {

    @Published var textOutputToScreen: String = "Enter Name"

但是,当我的CalculatorView结构更改textOutputToScreen的值时,整个事情崩溃了……我发现的所有帮助都说是要在SceneDelegate中设置GlobalEnvironment,但我已经做到了。我想念什么?

1 个答案:

答案 0 :(得分:0)

我在您的代码中看不到任何按钮。因此,我根据您向我展示的内容制作了该程序,并且可以正常工作。

SceneDelegate:

import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    var env = GlobalEnvironment()

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = CalculatorView().environmentObject(env)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

然后显示CalculatorView:

import SwiftUI

struct CalculatorView: View {
    
    @EnvironmentObject var env: GlobalEnvironment
    
    var body: some View {
        HStack {
            Spacer()
            Text(env.textOutputToScreen)
        }
    }
}

然后是GlobalEnvironment:

import SwiftUI

class GlobalEnvironment: ObservableObject {
    @Published var textOutputToScreen = "Enter Name"
}

这给了我这个结果,这就是代码应该产生的结果。 enter image description here