[英]SwiftUI - How to pass EnvironmentObject into View Model?
[英]how to use EnvironmentObject in a Swiftui View function?
最后,我發現了問題。 我質疑的視圖被放置在一個 .sheet 中。 如果我單獨顯示此視圖,環境變量將起作用,但如果將它們放在 .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
而您不在SceneDelegate.swift加載的視圖中
如果您以正確的方式使用 EnvObject,您只需要將 EnvObject 傳遞給下一個視圖,如下所示:
DestinationView().environmentObject(self.yourEnvObject)
我的帖子中解釋了更多信息: https : //stackoverflow.com/a/58997326/12378791
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.