这感觉很基本,但我无法让它工作。从FIrestore读取的内容不会显示在tableview中。据我所知,tableview 是在从 FIrestore 填充 scheduleArray
数组之前渲染的。如果我使用 scheduleArray
文字,一切都会正常工作。
loadData() 函数中的打印语句可以很好地打印数据库的内容。因此,与 Firestore 的连接按预期工作。
如何在渲染表格 View 之前进行数据库读取和数组填充?
class ListScheduleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var scheduleIDarray = [String]() // <-- If this is made an array literal, everything works
var db: Firestore!
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
loadData()
}
func loadData() {
db.collection("schedules").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
self.scheduleIDarray.append(document.documentID)
}
}
print(self.scheduleIDarray) // <-- This prints the content in db correctly
}
}
@IBOutlet weak var tableView: UITableView!
//Tableview setup
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Tableview setup \(scheduleIDarray.count)")
return scheduleIDarray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customScheduleCell", for: indexPath) as! customScheduleviewCell
let schedule = scheduleIDarray[indexPath.row]
cell.scheduleName.text = schedule
print("Array is populated \(scheduleIDarray)")
return cell
}
}
最佳答案
在 viewController 中创建 tableView 的 socket :
@IBOutlet weak var tableView: UITableView!
并在 viewDidLoad()
中写入给定的行
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
成功接收数据后重新加载tableView。
关于swift - 从 Firestore 填充 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49766747/