ios - 有没有办法用数组构造一个 Firestore 字段(同名)并显示 TableView 中每个字段的每个数组元素

标签 ios arrays swift firebase google-cloud-firestore

我正在开发一个 IOS 应用程序,我想在表格 View 中显示来自所有文档字段的数组字符串。

这是我的数组结构。

struct Test{
    var car: Array<String>


    var dictionary: [String: Any] {
        return [
            "car":car
        ]
    }


}

extension Test{
    init?(dictionary: [String : Any]) {
            guard let car = dictionary["car"] as? Array<String>
            else { return nil }

        self.init(car:car)
    }
}

这是我获取数据的代码。

func loadData(){

        let db = Firestore.firestore()

        db.collection("test").getDocuments(){
            querySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            }else{
                self.testArray = querySnapshot!.documents.compactMap({Test(dictionary: $0.data())})
                print(self.testArray)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }

    }

这是我的 tableView 代码。

override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let item = testArray[indexPath.row].car[indexPath.row]

        cell.textLabel!.text = ("\(item)")

        return cell

一切看起来都很好,但是当运行应用程序时,tableview 在第一行显示第一个文档的 [0],在第二行显示第二个文档的 [1] 等等。我想显示整个数组第一个文档,然后是第二个文档中的整个数组,等等。

最佳答案

你需要多个部分

override func numberOfSections(in tableView: UITableView) -> Int {
   return testArray.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return testArray[section].car.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)   
    cell.textLabel!.text = testArray[indexPath.section].car[indexPath.row] 
    return cell
 }

关于ios - 有没有办法用数组构造一个 Firestore 字段(同名)并显示 TableView 中每个字段的每个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656516/

相关文章:

android - 如何获取有关电话的信息

ios - 异步加载和 UITableView 的 -reloadData

arrays - 用 PySpark 中的对应元素替换数组中的元素

ios - 模型类、json编码和继承

swift - 重新加载 UITableView 后如何保持突出显示的多个 UITableView 行?

iphone - 我应该如何在 iPhone 应用程序中管理和引用多个图像文件?

ios - 自动布局(约束)与自动调整大小掩码(Springs & Struts)

javascript - 数组名实例数组;没有按预期工作

python - 如何从文件中读取Python数组?

ios - 如何解决 Swift 中的这种类型不明确的错误?