首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EnvironmentVariables在SwiftUI中将变量从一个视图传递到另一个视图时不工作

EnvironmentVariables在SwiftUI中将变量从一个视图传递到另一个视图时不工作
EN

Stack Overflow用户
提问于 2020-02-03 05:19:46
回答 1查看 396关注 0票数 1

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

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

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

下面是如何在SwiftUI中将变量从一个视图传递到另一个视图中给出的示例,下面是ContentView中包含的代码:

代码语言:javascript
复制
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的内容:

代码语言:javascript
复制
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) {
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-02-03 05:32:27

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

代码语言:javascript
复制
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environmentObject(_Your_object_here())
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60033468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档