Swift,访问 TableView 的数据

标签 swift uitableview firebase closures

所以,我加载了我的 firebase 节点,然后将数据追加到一个数组中以在 TableView 中使用,但出于某种原因我无法访问 planitTitles 中的数据,除非我在这个闭包中。请问,有什么解决方法吗?我觉得我以前已经做到了。谢谢

func loadFirebase(){
    let ref = Database.database().reference()
    let planits = ref.child("planits")

    planits.observe( .value, with: { (planitsSnapshot) in

                for child in planitsSnapshot.children {
                    let planSnap = child as! DataSnapshot
                    let planDict = planSnap.value as! [String: Any]

                if self.keyForThisPlanit.contains(planSnap.key){

                     let title = planDict["Planit Title"] as! String

                    self.planitTitles.append(title)

                        }
            }
        })
    print(self.planitTitles)

}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "friendUpdatesCell") as? ViewUpdatesTVCell else { return UITableViewCell() }


   cell.randomPlanitNumber.text = planitTitles[indexPath.row]
// CRASHES HERE WITH ERROR OUT OF INDEX
    return cell

}

最佳答案

for循环后需要重新加载表

var planitTitles = [String]()

//

func loadFirebase(){
    let ref = Database.database().reference()
    let planits = ref.child("planits")

    planits.observe( .value, with: { (planitsSnapshot) in
                self.planitTitles.removeAll() // you may want to clear here to avoid duplications 
                for child in planitsSnapshot.children {
                    let planSnap = child as! DataSnapshot
                    let planDict = planSnap.value as! [String: Any]                  
                    if self.keyForThisPlanit.contains(planSnap.key){
                        let title = planDict["Planit Title"] as! String
                           self.planitTitles.append(title)

                     }
                  }
             print(self.planitTitles)
             self.tableView.reloadData()
      })

}
func numberOfRows(inSection section: Int) -> Int {
    return planitTitles.count // to prevent cellForRowAt indexOutOfBounds crash
}

关于Swift,访问 TableView 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51313565/

相关文章:

ios - iOS 屏幕几何布局是如何工作的?

ios - 如何将标签栏添加到表格 View 而不是详细 View

ios - 如何创建一个可以自动调整高度的表格

javascript - 如何更新 firebase firestore 中的文档 ID?

swift - RxSwift和Moya同步请求

swift - Apple WatchKit 2 中主 Controller 的分层导航

swift - 如何快速调用按钮高度

ios - 如何交互式收缩和增长 Table View Cell?

firebase - Power BI api 连接到 Firebase 函数

javascript - 更新firestore中文档的createdAt和updatedAt日期字段的正确方法是什么?