我需要帮助来检索子项并将其添加到 TableView 中。子类称为“Title”,是“Post”的子类。我已成功检索所有帖子并打印出来,但我不知道如何将“标题”放入我的表格 View 中。
var posts = [postStruct]()
override func viewDidLoad() {
super.viewDidLoad()
let ref = FIRDatabase.database().reference().child("Posts")
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
print(rest.value!)
//need help here! I want to put the title which is a child of "Post"
}
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].title
return cell!
}
最佳答案
let ref = FIRDatabase.database().reference().child("Posts")
ref.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {
guard let value = rest.value as? Dictionary<String,Any> else { continue }
guard let title = value["Title"] as? String else { continue }
let post = postStruct(title: title)
self.posts.append(post)
}
self.tableView.reloadData()
})
关于swift - Firebase 在 TableView 中检索和插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824078/