在SwiftUI中将变量从一个视图传递到另一个视图时,EnvironmentVariables不起作用

时间:2020-02-03 05:19:46

标签: swiftui swiftui-environment

我发现了一些类似的示例,说明如何在SwiftUI的多个视图之间传递变量:

  1. Hacking with Swift - How to use @EnvironmentObject to share data between views
  2. How to pass variable from one view to another in SwiftUI

我正在尝试遵循示例,并使用EnvironmentVariables并修改ContentView在SceneDelegate中首次定义的位置。但是,在尝试这两个示例时,出现错误“编译失败:'ContentView_Previews'不是'环境'的成员类型”。我正在使用Xcode版本11.3.1。

按照How to pass variable from one view to another in SwiftUI中给出的示例,以下是ContentView中包含的代码:

class SourceOfTruth: ObservableObject{
    @Published var count = 0
}

struct ContentView: View {
    @EnvironmentObject var truth: SourceOfTruth
    var body: some View {
        VStack {
            FirstView()
            SecondView()
        }
    }
}

struct FirstView: View {
    @EnvironmentObject var truth: SourceOfTruth
    var body: some View {
       VStack{
        Text("\(self.truth.count)")
           Button(action:
            {self.truth.count = self.truth.count-10})
           {
               Text("-")
           }
       }
    }
}

struct SecondView: View {
    @EnvironmentObject var truth: SourceOfTruth
    var body: some View {
        Button(action: {self.truth.count = 0}) {
            Text("Reset")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(SourceOfTruth())
    }
}

...这是SceneDelegate的内容:

import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    var truth = SourceOfTruth() // <- Added

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    //    let contentView = ContentView()
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(SourceOfTruth())) // <- Modified
            self.window = window
            window.makeKeyAndVisible()
        }
    }
    func sceneDidDisconnect(_ scene: UIScene) {
    }
    func sceneDidBecomeActive(_ scene: UIScene) {
    }
    func sceneWillResignActive(_ scene: UIScene) {
    }
    func sceneWillEnterForeground(_ scene: UIScene) {
    }
    func sceneDidEnterBackground(_ scene: UIScene) {
    }
}

1 个答案:

答案 0 :(得分:1)

我不依赖Xcode版本,这不是问题。您必须像在ContentView中一样在ContentView_Previews中设置SceneDelegate,并提供.environmentObject,如下例所示

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(_Your_object_here())
    }
}