如何使用SwiftUI EnvironmentObject进行引用

时间:2019-10-12 10:55:34

标签: swift swiftui

根据Apple官方指南,我猜测每个视图是否只有一个环境对象,那么这样做就可以了。当碰巧不止一个时,我不确定如何引用该对象。

struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData
...
 ForEach(userData.landmarks) { landmark in
                    if !self.userData.showFavoritesOnly || landmark.isFavorite {
                        NavigationLink(
                            destination: LandmarkDetail(landmark: landmark)
                                .environmentObject(self.userData)

                        ) {
                            LandmarkRow(landmark: landmark)
                        }
                    }
                }

上面是Apple官方指南中的代码,位于LandMarkDetail文件中

struct LandmarkDetail: View {
    @EnvironmentObject var userData: UserData

我想知道LandMarkList中的environmentObject如何引用到LandmarkDetail中的环境对象。他们被束缚了吗? 我在文件中添加了第二个EnvironmentObject,但是什么也没发生

struct LandmarkDetail: View {
    @EnvironmentObject var userData: UserData
    @EnvironmentObject var testData: UserData

那么如何引用每个userData和testData

编辑: 我试图在以下文件中添加环境对象:

import SwiftUI

struct LandmarkList: View {
    @EnvironmentObject private var userData: UserData
    @EnvironmentObject private var testData: TestData
    var body: some View {
        NavigationView {
            List {
                Toggle(isOn: $userData.showFavoritesOnly) {
                    Text("Show Favorites Only")
                }
                Toggle(isOn: $testData.testbool) {
                                   Text("Test")
                }
...
struct LandmarksList_Previews: PreviewProvider {
    static var previews: some View {
        ForEach(["iPhone SE", "iPhone XS Max"], id: \.self) { deviceName in
            LandmarkList()
                .previewDevice(PreviewDevice(rawValue: deviceName))
                .previewDisplayName(deviceName)
        }
        .environmentObject(UserData())
        .environmentObject(TestData())
    }
}
final class TestData: ObservableObject {
    @Published var testbool = false
}

预览崩溃。 Xcode可以编译,但立即出现以下错误

Fatal error: No ObservableObject of type TestData found.
A View.environmentObject(_:) for TestData may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-30.4/Core/EnvironmentObject.swift, line 55
2019-10-12 19:07:46.565707+0800 Landmarks[13034:643289] Fatal error: No ObservableObject of type TestData found.
A View.environmentObject(_:) for TestData may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-30.4/Core/EnvironmentObject.swift, line 55

1 个答案:

答案 0 :(得分:1)

不要忘记在Scenedelegate中绑定对象:

window.rootViewController = UIHostingController(rootView: contentView.environmentObject(TestData()).environmentObject(UserData()))