swift - 数组未在 Swift 中更新

标签 swift google-cloud-firestore

当您启动应用程序时,您应该从 Firestore 文档中获取一行并写入一个数组, (数组)

    var items = [String]()
override func viewDidLoad() {
        let db = Firestore.firestore()
        db.collection("cities").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                    self.items.append(document.data()["title"] as! String)
                }
            }
        }

    }

然后在单元格创建函数中,文本应更改为数组中的一行。

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! colCell
        print(self.items)
        cell.myLabel.text = self.items[indexPath.item]

        return cell
    }

但是包含来自 firestore 的字符串的数组不会在单元格创建函数中更新。为什么?

(我在 viewDidLoad 和单元格中打印了数组,它在 viewDidLoad 中更新了,但没有在单元格中更新)

最佳答案

您需要重新加载 collectionView,因为对 firestore 的调用是异步的

for document in querySnapshot!.documents {
   print("\(document.documentID) => \(document.data())")
   self.items.append(document.data()["title"] as! String)
}
self.collectionView.reloadData()

关于swift - 数组未在 Swift 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55329660/

相关文章:

ios - Swift:在 tableView 中搜索 JSON 数据

ios - 在 ARKit 中获取一个点的绝对位置

javascript - 如何从 Firestore 取回整个数组而不是对象?

swift - 如何使用 Swift 异步方法从后端数据库中检索数据?

ios - 自定义单元格和默认单元格同时显示在 tableview 上

ios - 为什么 UIBarButtonItem 显示为已禁用?

android - Android 上的 Firebase Firestore GetInstance 失败

javascript - 如何按单个页面对 Firestore 数据集进行分页?

java - Firestore ui 适配器错误 java.lang.NullPointerException : 'void com. firebase.ui.firestore.FirestoreRecyclerAdapter.startListening()

javascript - 网络应用 : Firestore cache - read changed documents only