swiftui - SwiftUI 中的 ForEach 循环仅在数组中显示第一个
问题描述
我正在尝试使用 SwiftUI 中的 ForEach 显示从 firebase 获取的数组。
但是,它只显示数组第一个索引的标题。
似乎它确实记录了数组中有多少项,因为它根据数组中的项数显示正确的视图数,但每个项只有第一项的标题。
如何让它显示数组中所有项目的标题?
我像这样获取项目:
class ProjectRepository: ObservableObject
{
private var cancellables: Set<AnyCancellable> = []
private let store = Firestore.firestore()
@Published var projects: [Project] = []
init()
{
get()
}
// Retrieve projects from firebase
func get()
{
store.collection(FirestoreKeys.CollectionPath.projects)
.addSnapshotListener { querySnapshot, error in
if let error = error {
print("Error getting projects: \(error.localizedDescription)")
return
}
self.projects = querySnapshot?.documents.compactMap{ document in
try? document.data(as: Project.self)
} ?? []
}
}
// Add projects to firebase
func add(_ project: Project)
{
do {
_ = try store.collection(FirestoreKeys.CollectionPath.projects).addDocument(from: project)
} catch {
fatalError("Unable to add card: \(error.localizedDescription)")
}
}
}
这是我的项目模型:
struct Project: Identifiable, Codable
{
@DocumentID var id: String?
var title: String
var image: String
@ServerTimestamp var startDate: Date?
@ServerTimestamp var endDate: Date?
var tasks: [Task]
}
这是我的任务模型:
struct Task: Identifiable, Codable
{
@DocumentID var id: String?
var title: String
var done: Bool
}
最后,这就是我试图展示任务的方式:
ScrollView {
ForEach(projectViewModel.project.tasks) { task in
HStack {
Image(task.done ? "checkmark-filled" : "checkmark-unfilled")
RoundedRectangle(cornerRadius: 20)
.foregroundColor(.white)
.frame(height: 72)
.shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 4)
.overlay(Text(task.title))
.padding(.leading)
}
}
.padding()
}
解决方案
我想到了。这是因为该任务需要一个唯一的 ID,而它没有文档 ID。
我更换了
@DocumentID var id: String?
和
var id: String? = UUID().uuidString
并在 Firestore 中的任务中添加了一个 id 字段。
然后我通过调用显示列表中的任务
ForEach(projectViewModel.project.tasks, id: \.id) { task in
(Insert code here)
}
推荐阅读
- delphi - 调整列大小时的 Delphi、TVirtualStringTree、WM_SIZE 事件
- rest - 有没有办法将网络活动结果放入 sql-table (sink)
- javascript - 仅在关注移动设备后立即触发输入字段模糊事件
- c# - 带有字符串插值的新行
- html - 如何使用按钮提示下载 PDF?
- r - 检验零假设
- vhdl - vhdl:warning: 通用整数绑定必须是数字文字或属性
- sqlite - SQLite 将连字符视为算术运算符
- javascript - 如何与 AJAX 响应一起传递额外的变量?
- vue.js - VueJS - 使用过滤器或基础组件来格式化数字