找不到类型为PageSettings的ObservableObject

时间:2020-02-21 18:08:29

标签: swiftui ios13

我想使用其他视图来更改@EnvironmentObject的值。但是我得到这个错误。这是我的语法

我的班级

   class PageSettings: ObservableObject {
    @Published var currentPage = "splash"
    @Published var jobTitle = "Pick a job!"
}

视图(在此视图中,我将获得“选择工作!”作为文本,当我从另一个名为“ JobTitleView”的视图中单击另一个选项时,我想对其进行更改)

    struct Test: View {

    @EnvironmentObject var title: PageSettings

    var body: some View {
        HStack{
            Button(action: {
                let alertHC = UIHostingController(rootView: JobTitleView())

                alertHC.preferredContentSize = CGSize(width: 300, height: 200)
                alertHC.modalPresentationStyle = UIModalPresentationStyle.fullScreen

                UIApplication.shared.windows[0].rootViewController?.present(alertHC, animated: true)
            })
            {
                Text(self.title.jobTitle)

                Image(systemName: "chevron.down")
            }
        }.frame(height:50).font(.subheadline)
    }
}

JOBTITLE VIEW

struct JobTitleView: View {

    @EnvironmentObject var title: PageSettings
    let options = ["Manager", "Employee"]

    var body: some View {
        ForEach(options) { item in
            Button(action:{

                self.title.jobTitle = item
                UIApplication.shared.windows[0].rootViewController?.dismiss(animated: true, completion: {})
            }){
                Text(item).font(.custom("Avenir Next Regular", size: 30))
            }
        }
    }
}

当我按下一个项目时,出现以下错误:

严重错误:找不到类型为PageSettings的ObservableObject。 PageSettings的View.environmentObject(_ :)作为此视图的祖先可能会丢失:文件/BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-39.4.3/Core/EnvironmentObject.swift ,第55行

PS。我得到了扩展,可以使用ForEach“无ID”

extension String: Identifiable {
    public var id: String {
        return self
    }
}

1 个答案:

答案 0 :(得分:0)

在创建Test的地方,您必须将其用作

Test().environmentObject(PageSettings())

(很可能也是在此自定义创建中)(在视图构建器层次结构环境中,对象自动注入到子视图中,但在这种情况下,我认为不是)

let alertHC = UIHostingController(rootView: 
         JobTitleView().environmentObject(self.pageSettings))