读取数据库后,UITableViewController加载numberOfRowsInSection

时间:2018-07-22 13:03:43

标签: ios swift uitableview

读取数据库后如何使UITableViewController加载numberOfRowsInSection?

override func viewWillAppear(_ animated: Bool) {             
    let ref = Database.database().reference()
    ref.child("key").observeSingleEvent(of: .value, with: { (snapshot) in
         for child in snapshot.children{
             let data = child as! DataSnapshot
             let key = story.key
             self.KeyArray.append(key)
          }
    })
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.storyKeyArray.count // this returns 0, expectedly...
}

类似地,我也只希望在读取数据库之后加载“ cellForRowAt”函数。谢谢!

2 个答案:

答案 0 :(得分:1)

只要numberOfRowsInSection返回0,就不会调用cellForRowAt

读取数据库后,在表视图上调用reloadData()。确保在主线程上执行此操作。

ref.child("key").observeSingleEvent(of: .value, with: { (snapshot) in
      for child in snapshot.children{
         // ... populate storyKeyArray somehow ...
      }
      DispatchQueue.main.async {
          self.tableView.reloadData()
      }
})

这将再次使您的数据源方法称为 ,这次storyKeyArray将具有非零的count,而您的cellForRowAt:将被称为供应细胞。

答案 1 :(得分:0)

读取数据库后,必须重新加载表视图