【发布时间】:2021-05-29 21:00:28
【问题描述】:
这是我的第一个 SwiftUI 项目,在编程方面非常新。
我的内容视图有一个视图模型和一个选择器,设法将 $selection 发送到详细视图,但不知道如何让它再次从 Firestore 中读取。我有点觉得缺少了什么,就像我需要使用 if-else,但无法准确指出问题所在。在这里搜索了论坛,但似乎找不到解决方案。
这是虚拟机
import Foundation
import Firebase
class FoodViewModel: ObservableObject {
@Published var datas = [Food]()
private var db = Firestore.firestore()
func fetchData(){
db.collection("meals").addSnapshotListener { (snap, err) in
DispatchQueue.main.async {
if err != nil {
print((err?.localizedDescription)!)
return
} else {
for i in snap!.documentChanges{
let id = i.document.documentID
let name = i.document.get("name") as? String ?? ""
let weight = i.document.get("weight") as? Int ?? 0
let temp = i.document.get("temp") as? Int ?? 0
let time = i.document.get("time") as? Int ?? 0
self.datas.append(Food(id: id, name: name, weight: weight, temp: temp, time: time))
}
}
}
}
}
}
struct ContentView: View {
@ObservedObject var foodDatas = FoodViewModel()
@State private var id = ""
@State public var selection: Int = 0
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Picker(selection: $selection, label: Text("Select your food")) {
ForEach(allFood.indices, id:\.self) { index in
Text(allFood[index].name.capitalized).tag(index)
}
}
.onAppear() {
self.foodDatas.fetchData()
}
Spacer()
NavigationLink(
destination: DetailView(selection: self.$selection),
label: {
Text("Let's make this!")
.font(.system(size: 20))
.fontWeight(.bold)
.foregroundColor(Color.black)
.padding(12)
})
}
在选择器选择食物类型后,我希望它显示烹饪时间和温度等其余细节。现在它显示文本部分的“索引超出范围”。
import SwiftUI
import Firebase
struct DetailView: View {
@ObservedObject var foodDatas = FoodViewModel()
@Binding var selection: Int
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Text("Cooking Time: \(allFood[selection].time) mins")
}
}
}
}
感谢我能得到的所有帮助。
【问题讨论】:
标签: google-cloud-firestore swiftui picker