当您启动应用程序时,您应该从 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/