简体   繁体   English

如何在 Swiftui View 函数中使用 EnvironmentObject?

[英]how to use EnvironmentObject in a Swiftui View function?

Resolved解决

Finally, I found the problem.最后,我发现了问题。 My questioned View was placed in a .sheet.我质疑的视图被放置在一个 .sheet 中。 If I show this View separately, the environment variables will work, but if they are placed in .sheet, the Store must be explicitly injected in.如果我单独显示此视图,环境变量将起作用,但如果将它们放在 .sheet 中,则必须显式注入 Store。

.sheet(isPresented: $showEditSheet){
        EditFavoriteRootView().environmentObject(Store())
    }

Now It's worked!现在它起作用了!

old quesition老问题

Because ForEach couldn't support too complicated logic, I defined a function in the View to implement the content.因为 ForEach 不能支持太复杂的逻辑,所以我在 View 中定义了一个函数来实现内容。 In most cases, this is fine.在大多数情况下,这很好。 However, I cannot use the EnviromentObject in the function。但是,我不能在函数中使用EnviromentObject。

build success , the button in View body works fine, but when I click button in function got the runtime error:构建成功,视图主体中的按钮工作正常,但是当我单击函数中的按钮时出现运行时错误:

Fatal error: No ObservableObject of type Store found.
A View.environmentObject(_:) for Store may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros/Monoceros-

Code sample:代码示例:

struct FromCategory: View {
    @EnvironmentObject var store:Store

    var body: some View {
        ForEach(AppState.HealthCategoryList.keys.sorted(by: <),id:\.self){
            self.ShowList(categoryId: $0)
        }
        Button(action:{
           self.store.dispatch(.updateFavorite(idName:"test"))
        }){Text("Test")}

    }

    func ShowList(categoryId:String)->some View{

        let metalist = AppState.HealthCategoryList[categoryId]?.metaData?.sortedArray(using: [NSSortDescriptor(key: "idName", ascending: true)]) as! [HealthMetaData]

        return VStack{
            VStack(spacing:10)  {
                ForEach(0..<metalist.count){i in
                    HStack{
                        Text(metalist[i].title!)
                        Spacer()
                        Button(action:{
                            self.store.dispatch(.updateFavorite(idName: metalist[i].idName!))
                            //self.store.appState.updateFavorite(idName: metalist[i].idName!)
                        }){
                            if AppState.UserFavoriteList[metalist[i].idName!] != nil {
                                Image(systemName: "star.fill")
                            }
                            else {
                                Image(systemName: "star")
                            }
                        }
                    }

                }
            }
        }

    }   

}

Fatal error: No ObservableObject of type Store found.致命错误:找不到类型为 Store 的 ObservableObject。 in this line在这一行

self.store.dispatch(.updateFavorite(idName: metalist[i].idName!))

store can be use well in normal some View, but not in function. store 可以在正常的某些 View 中很好地使用,但在函数中却无法使用。 How to solve this.如何解决这个问题。 Or is there any other way?或者还有其他方法吗? Thanks谢谢

This is happening because you want to update an EnvironmentObject and you're not in the View which was loaded by the SceneDelegate.swift发生这种情况是因为您想要更新EnvironmentObject而您不在SceneDelegate.swift加载的视图中

In case you're using the EnvObject in a correct way, you just need to pass te EnvObject to the next view like this:如果您以正确的方式使用 EnvObject,您只需要将 EnvObject 传递给下一个视图,如下所示:

DestinationView().environmentObject(self.yourEnvObject)

More information explained in my post: https://stackoverflow.com/a/58997326/12378791我的帖子中解释了更多信息: https : //stackoverflow.com/a/58997326/12378791

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM