我正在开发一个 IOS 应用程序,我想在表格 View 中显示来自所有文档字段的数组字符串。
这是我的数组结构。
struct Test{
var car: Array<String>
var dictionary: [String: Any] {
return [
"car":car
]
}
}
extension Test{
init?(dictionary: [String : Any]) {
guard let car = dictionary["car"] as? Array<String>
else { return nil }
self.init(car:car)
}
}
这是我获取数据的代码。
func loadData(){
let db = Firestore.firestore()
db.collection("test").getDocuments(){
querySnapshot, error in
if let error = error {
print("\(error.localizedDescription)")
}else{
self.testArray = querySnapshot!.documents.compactMap({Test(dictionary: $0.data())})
print(self.testArray)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
这是我的 tableView 代码。
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let item = testArray[indexPath.row].car[indexPath.row]
cell.textLabel!.text = ("\(item)")
return cell
一切看起来都很好,但是当运行应用程序时,tableview 在第一行显示第一个文档的 [0],在第二行显示第二个文档的 [1] 等等。我想显示整个数组第一个文档,然后是第二个文档中的整个数组,等等。
最佳答案
你需要多个部分
override func numberOfSections(in tableView: UITableView) -> Int {
return testArray.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testArray[section].car.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = testArray[indexPath.section].car[indexPath.row]
return cell
}
关于ios - 有没有办法用数组构造一个 Firestore 字段(同名)并显示 TableView 中每个字段的每个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55656516/