【发布时间】:2020-03-28 03:06:37
【问题描述】:
已解决
终于,我找到了问题所在。我质疑的视图被放置在.sheet 中。如果我单独展示这个View,环境变量会起作用,但是如果放在.sheet中,必须显式注入Store。
.sheet(isPresented: $showEditSheet){
EditFavoriteRootView().environmentObject(Store())
}
现在成功了!
老问题
因为 ForEach 无法支持太复杂的逻辑,所以我在 View 中定义了一个函数来实现内容。 在大多数情况下,这很好。但是,我不能在函数中使用EnviromentObject。
构建成功,视图主体中的按钮工作正常,但是当我单击函数中的按钮时出现运行时错误:
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-
代码示例:
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")
}
}
}
}
}
}
}
}
致命错误:未找到 Store 类型的 ObservableObject。在这一行
self.store.dispatch(.updateFavorite(idName: metalist[i].idName!))
store在一些View中可以正常使用,但在功能上不行。 如何解决这个问题。或者还有其他方法吗? 谢谢
【问题讨论】:
-
您是否使用
.environmentObject()将环境对象注入到您的视图中? -
让 contentView = MainTab() .environment(\.managedObjectContext, context) .environmentObject(Store()) 是的,我做到了