我有一個用戶界面,其中包含用戶可以點擊的專案串列。這將打開一個詳細視圖,其中列出了一個專案的所有詳細資訊。但是,我想在該詳細視圖中包含 2 個值,這些值存盤在 Firestore 的不同集合中,并且也有自己的資料模型結構。這樣做的原因是不同的應用程式與該集合一起使用,我想將“共享”集合與其他集合分開。
我有一個函式從 Firestore 中提取這兩個值done
這個函式將值傳遞給我的資料模型中名為 CareData 的結構done
我想我在詳細視圖中正確設定了所有內容,但問題是從表格串列到詳細視圖。
讓我試著解釋一下我對我的代碼做了什么:
資料模型
只是簡單的陣列,沒有什么復雜的。
struct Items: Decodable, Identifiable {
var id: String
var name: String
…
}
struct CareData {
var avHeight: Int
var avWater: Int
}
詳細視圖
struct Detail: View {
@EnvironmentObject var model: ViewModel
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
// Passing the model instances
let item: Items
let care: CareData
var body: some View {
// Some (working) code where data like item.name is shown.
...
// The 2 values using the CareData Data Model
Text("Height: \(care.avHeight)")
Text("Water: \(care.avWater)")
}
}
查看模型
這里有一個重要說明:我的共享集合中的檔案以非共享集合的專案名稱命名。當我呼叫該函式時,我使用 item.name 來查詢共享集合中的正確檔案。
class ViewModel: ObservableObject {
@Published var itemList = [Items]()
@Published var careData = [CareData]()
...
func getCareData(item: String) {
// Some code that gets the data in Firestore from the shared collection and appends it to careData. It is working all well.
}
}
NavigationLink 中有問題的串列視圖
Detail() 期望我傳遞 2 個引數,因為我試圖在詳細視圖中傳遞兩個模型實體。我了解使用item: item,因為我正在遍歷所有專案并且需要定義詳細視圖所需的內容。但是我需要添加care:什么?
struct PlantList: View {
@EnvironmentObject var model: ViewModel
var body: some View {
ForEach(model.itemList) { item in
NavigationLink(destination: Detail(item: item, care: ?????? )) { // XCode proposing to go for "CareData", but then throws the error "Cannot convert value of type 'CareData.Type' to expected argument type 'CareData'"
Text(item.name)
}
.onAppear {
model.getCareData(item: item.name)
}
}
}
}
我嘗試了一些奇怪的事情,比如CareDate.init(avHeight: , avWater:)當我將數字直接寫入代碼時它起作用了,但我需要變數不是我想出的一些靜態數字。
我希望有人能幫幫忙。我想要的只是在詳細視圖中顯示 2 個值。這可能是一個愚蠢的問題,但我很沮喪,因為我似乎還不了解 Swift 編程的基礎知識。
uj5u.com熱心網友回復:
嘗試這樣的事情(當然未經測驗,因為我沒有你的資料庫),如果你只想要第一個元素:
EDIT-1:更新
struct PlantList: View {
@EnvironmentObject var model: ViewModel
var body: some View {
ForEach(model.itemList) { item in
NavigationLink(destination: Detail(item: item, care: model.careData.first ?? CareData(avHeight: 0, avWater: 0))) {
Text(item.name)
}
.onAppear {
model.getCareData(item: item.name)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522868.html
標籤:IOS迅速
上一篇:洗掉ReorderableListView中的空白/填充
下一篇:pta第二次博客
