[英]Swift 3 Writing Firebase Data to TableView
I am fetching all user id's from my Firebase database. 我正在从Firebase数据库中获取所有用户ID。 When I execute the program I can see snapshot of all user id's on console via code in line 26. But the code is not writing to table cells.
当我执行该程序时,可以通过第26行的代码在控制台上看到所有用户ID的快照。但是该代码未写入表单元格。 I done this with tutorial.
我是通过教程完成的。 Everything is same with video.
视频一切都一样。 But it does not work for me Where is the problem ?
但这对我不起作用问题出在哪里?
class ChatInfo: UITableViewController {
let cellId = "cellId"
var users = [User] ()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Geri", style: .plain, target:self, action: #selector(handleCancel))
fetchUser()
}
func handleCancel() {
dismiss(animated: true, completion: nil)
}
func fetchUser() {
Database.database().reference().child("locations").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.userId = dictionary["userId"] as! String
print(user.userId) // IT PRINTS ALL USERS TO CONSOLE
self.users.append(user)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
} , withCancel: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
let user = users[indexPath.row]
cell.detailTextLabel?.text = user.userId
return cell
}
}
You are overriding the wrong method 您要覆盖错误的方法
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
And design the cell style in Interface Builder and use this method in cellForRowAt
并在Interface Builder中设计单元格样式,并在
cellForRowAt
使用此方法
let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath)
As per your requirement actual way for fetching records of tableview cell is this: 根据您的要求,获取tableview单元格记录的实际方式是这样的:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath)
let user = users[indexPath.row]
cell.detailTextLabel?.text = user.userId
return cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.