我发现了一些类似的例子,说明如何在SwiftUI中的多个视图之间传递变量:
我正在尝试遵循这些示例,使用EnvironmentVariables并修改ContentView,在SceneDelegate中首先定义它。但是,在尝试这两个示例时,我会得到“编译失败:'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) {
}
}发布于 2020-02-03 05:32:27
我不依赖Xcode版本,这也不是一个问题。您必须以与在ContentView中相同的方式在ContentView_Previews中设置.environmentObject,提供.environmentObject,如下例所示
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(_Your_object_here())
}
}https://stackoverflow.com/questions/60033468
复制相似问题