【问题标题】:Save array in Firestore and display it in the uitableview in Swift在 Firestore 中保存数组并在 Swift 的 uitableview 中显示它
【发布时间】:2020-09-28 11:27:29
【问题描述】:

我正在使用 Swift 和 Firestore,我在其中收集任务。

我用任务数据填充每个 tableview 单元格。有一个字段标签。现在它只是一个字符串,但我希望它是一个字符串数组。
如何在任务模型中保存字符串数组并在表格视图中正确显示?

我的任务模型文件:

import Foundation
import FirebaseFirestore

protocol DocumentSerializable {
    init?(dictionary:[String:Any])
}

struct Task {
    var title: String
    var description: String
    var tip: String
    var hashtags: String

    var dictionary:[String:Any] {
        return [
            "title": title,
            "description": description,
            "tip": tip,
            "hashtags": hashtags
        ]
    }
}

extension Task : DocumentSerializable {

    init?(dictionary: [String : Any]) {

            let title = dictionary["title"] as? String ?? "Error! Title Field Not Found!"
            let description = dictionary["description"] as? String ?? "Error! Description Field Not Found!"
            let tip = dictionary["tip"] as? String ?? "Error! Tip Field Not Found!"
            let hashtags = dictionary["hashtags"] as? String ?? "Error! Hashtags Field Not Found!"

        self.init(title: title, description: description, tip: tip, hashtags: hashtags)
    }
}

我的 TableViewViewController 文件:

    import UIKit
    import Firebase
    import FirebaseAuth
    import FirebaseFirestore

    class TasksListScreen: UIViewController {

        var db = Firestore.firestore()
        var tasksArray = [Task]()

        @IBOutlet weak var tableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            loadData()
    }

    // load data from the user tasks collection to the table view
    func loadData() {

        let userID = Auth.auth().currentUser!.uid
        let userTasksCollRef = db.collection("users").document(userID).collection("tasks")

        userTasksCollRef.getDocuments { (queryShapshot, error) in
            if let error = error {
                print("Error loading data: \(error.localizedDescription)")
            } else {
                self.tasksArray = queryShapshot!.documents.compactMap({Task(dictionary: $0.data())})

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

extension TasksListScreen: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasksArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell") as! TaskViewCell

        let task = tasksArray[indexPath.row]

        cell.previewTitleLabel.text = task.title
        cell.previewMotivLabel.text = task.description
        cell.previewTipLabel.text = task.tip
        cell.previewHashtagsLabel.text = task.hashtags

        cell.cellDelegate = self
        cell.index = indexPath

        return cell
    }
    }

【问题讨论】:

  • 您遇到了什么问题?
  • 您好!我不知道如何在我的任务模型中正确地将主题标签字段存储为数组而不是字符串。

标签: ios arrays swift firebase google-cloud-firestore


【解决方案1】:

首先,您应该修改Task 中的hashtags 属性和init?(dictionary:) 方法。像这样:

struct Task {
    var title: String
    var description: String
    var tip: String
    var hashtags: [String]

    var dictionary:[String: Any] {
        return [
            "title": title,
            "description": description,
            "tip": tip,
            "hashtags": hashtags
        ]
    }
}

extension Task: DocumentSerializable {

    init?(dictionary: [String : Any]) {

            let title = dictionary["title"] as? String ?? "Error! Title Field Not Found!"
            let description = dictionary["description"] as? String ?? "Error! Description Field Not Found!"
            let tip = dictionary["tip"] as? String ?? "Error! Tip Field Not Found!"
            let hashtags = dictionary["hashtags"] as? [String] ?? ["Error! Hashtags Field Not Found!"]

        self.init(title: title, description: description, tip: tip, hashtags: hashtags)
    }
}

那么你需要修改cellForRow方法的下面一行来传递数组并正确显示。

修改这个:

cell.previewHashtagsLabel.text = task.hashtags

收件人:

cell.handleHashTags(task.hashtags)

您需要在TaskViewCell 类中添加一个名为handleHashTags 的新方法,并处理传递的字符串数组[String] 以显示它们。

【讨论】:

  • 谢谢!我创建了一个 func handleHashtags(hashtags: [String]) { } 。我该如何实现它?
  • 我想通了 :) 再次感谢您的帮助!
  • 我建议不要向解析数据的表格视图单元格(特别是如果它是可重用的)添加方法。您应该在渲染单元格之前解析所有数据;要求单元解析数据是一种不好的模式。在它到达数据源之前做它,而不是在数据源中,尤其是在单元格之后。
  • @VeronikaBabii 在 cellForRowAt 方法之前将数组拆分为字符串。在牢房里做这件事不是一个好主意。
猜你喜欢
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多