swift - 从 Firestore 填充 UITableView

标签 swift uitableview google-cloud-firestore

这感觉很基本,但我无法让它工作。从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/

相关文章:

swift - 通过滑动从 NSTableview 中删除行

ios - SwiftUI:通过数据库连接实现评级 View

iphone - 一个 UITableView 中的两种不同的单元格类型

ios - 如何在 UITableViewCell 中重用 UIView 的 xib 子类

firebase - Firestore 规则 : How to allow nested document read based on parent property

ios - 来电时截图

swift - 我可以使用 if 来比较包含参数的枚举吗?

ios - "cellForRowAtIndexPath"未调用 alertviewcontroller 内的 TableView

android - onSuccessTask 与 addOnSuccessListener?

firebase - Firestore 按两个字段排序