Antonio Labra
Antonio Labra

Reputation: 2010

No ObservableObject of type PageSettings found

I want to change the value of my @EnvironmentObject using a different view to call it. But I get this error. Here's my syntaxes

MY CLASS

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

A VIEW (In this view I get "Pick a job!" as a text and I want to change it when I clicked another option from another view called "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))
            }
        }
    }
}

When I pressed an item I got the following error:

Fatal error: No ObservableObject of type PageSettings found. A View.environmentObject(_:) for PageSettings may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-39.4.3/Core/EnvironmentObject.swift, line 55

PS. I got an extension to use a ForEach "without id"

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

Upvotes: 0

Views: 99

Answers (1)

Asperi
Asperi

Reputation: 258345

In the place where you create Test you have to use it as

Test().environmentObject(PageSettings())

and most probably in this custom creation as well (in view builder hierarchy environment object is injected automatically for subview, but in this case I suppose it is not)

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

Upvotes: 1

Related Questions