1

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

  1. Hacking with Swift - 如何使用@EnvironmentObject 在视图之间共享数据
  2. 如何在 SwiftUI 中将变量从一个视图传递到另一个视图

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

按照如何在 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) {
    }
}
4

1 回答 1

1

我不依赖 Xcode 版本,这不是问题。ContentView您必须以与在提供ContentView_Previews中相同的方式进行设置,如下例所示SceneDelegate.environmentObject

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(_Your_object_here())
    }
}
于 2020-02-03T05:32:27.690 回答