当您启动应用程序时,您应该从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()
你可以像这样更新日期后重新加载给定的单元格,
collectionView.reloadItemsAtIndexPaths(arrayOfIndexPaths)
它是更新UICollectionView的优化方式。