SwiftUI 中的 ForEach 循环仅在数组中显示第一个

时间:2021-01-10 09:00:04

标签: swiftui

我正在尝试使用 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()
}

1 个答案:

答案 0 :(得分:0)

我想通了。这是因为任务需要一个唯一的 ID 而它没有文档 ID。

我替换了

@DocumentID var id: String?

var id: String? = UUID().uuidString

并为 Firestore 中的任务添加了一个 id 字段。

然后我通过调用显示列表中的任务

ForEach(projectViewModel.project.tasks, id: \.id) { task in
 (Insert code here)
}
相关问题