[英]Computed Property from Child Struct Not Updating in SwiftUI
我的 SwiftUI 應用程序中有一個數據模型,如下所示:
struct Entry: Identifiable{
var id = UUID().uuidString
var name = ""
var duration: Int{
//An SQLite query that returns the total of the "duration" column
let total = try! dbc.scalar(tableFlight.filter(db.entry == id).select(db.duration.total))
return Int(total)
}
}
struct Flight: Identifiable{
var id = UUID().uuidString
var duration = 0
var entry: String?
}
我有一個ObservableObject
視圖模型,它產生這樣的條目:
class EntryModel: ObservableObject{
static let shared = EntryModel()
@Published var entries = [Entry]()
init(){
get()
}
func get(){
//Stuff to fetch the entries
entries = //SQLite query that returns an array of Entry objects
}
}
最后,在我的View
,我列出了所有條目名稱及其相關的duration
如下所示:
ForEach(modelEntry.entries){ entry in
VStack{
Text(entry.name) //<-- Updates fine
Text(entry.duration) //<-- Gets set initially, but no updates
}
}
我遇到的問題是,當我更新該Entry
的Flight
時,我視圖中的duration
不會更新。 我知道這不會發生,因為只有entries
會在更改時重繪。
但即使我在EntryModel
手動調用get()
函數,關聯的duration
仍然不會更新。
有一個更好的方法嗎? 如何在更新其子元素時重新計算父級的計算屬性?
我想到了。 我的實際代碼在VStack
所在的ForEach
中使用了一個子View
。 我只是向它傳遞一個entry
,所以這些值只是最初設置,因此不是反應性的。
通過將該entry
更改為Binding
,它可以正常工作:
ForEach($modelEntry.entries){ $entry in
ChildView(entry: $entry)
}
請注意, $
在$modelEntry
和返回$entry
是一個Xcode 13+功能(但到iOS 14和MacOS 11.0向后兼容)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.