数组未在Swift中更新

问题描述 投票:0回答:2

当您启动应用程序时,您应该从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中更新,未在单元格中更新)

swift google-cloud-firestore
2个回答
1
投票

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

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

0
投票

你可以像这样更新日期后重新加载给定的单元格,

collectionView.reloadItemsAtIndexPaths(arrayOfIndexPaths)

它是更新UICollectionView的优化方式。

© www.soinside.com 2019 - 2024. All rights reserved.