该文档在FirebaseUI上很少。如何使用FirebseUI将不同的数据源用于表格视图?
对于使用单个数据源的表视图,可以使用FUIFirestoreTableViewDataSource
或FirebaseTableViewDataSource
。您可以使用查询(例如FIRQuery
)将它们中的任何一个绑定到表视图,因此:
let query: Query = self.db.collection("users").whereField("name", isEqualTo: "Taiwo")
self.dataSource = self.tableView.bind(toFirestoreQuery: query) { tableView, indexPath, snapshot in
// get your data type out of the snapshot, create and return your cell.
}
这对于具有“单一真相源”的表视图非常有效,并且使您的表视图对数据库中的更改等做出了反应,而无需您做很多工作。
但是,在需要动态更改数据的情况下(例如,需要根据用户选择显示不同的数据),将无法使用数据源。在这种情况下,您需要使用Firebase的后备集合,例如FUIBatchedArray
或FUIArray
。
这与在表视图的数据源旁边使用Swift数组没什么不同。唯一的区别是您通常需要使用viewcontroller作为其委托来初始化数组:
var datasourceArray = FUIBatchedArray(query: query, delegate: self)
然后
extension MyViewController: FUIBatchedArrayDelegate {
func batchedArray(_ array: FUIBatchedArray, didUpdateWith diff: FUISnapshotArrayDiff<DocumentSnapshot>) {
// you'll receive changes to your array in `diff` and `array` is a whole array with
// all new changes together with old data
datasourceArray = array
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func batchedArray(_ array: FUIBatchedArray, willUpdateWith diff: FUISnapshotArrayDiff<DocumentSnapshot>) {
}
func batchedArray(_ array: FUIBatchedArray, queryDidFailWithError error: Error) {
}
}
然后您可以像在UITableViewDataSource方法中使用Swift数组一样使用datasourceArray
:
extension MyViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasourceArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let snapshot = datasourceArray.object(at: indexPath.row)
do {
let task = try snapshot.data(as: Task.self)
// create, customise and return your cell
}
}
catch {
print("coudln't get data out of snapshot", error.localizedDescription)
}
return UITableViewCell()
}
}