[英]How to reflect childChanges on tableView - IOS Swift Firebase
I have a tableview and would like to add childChange function to my tableview, but I have tried to do so, and instead updating the Child, my Tableview adds another row with the changed child, so I have one old valued row and new updated row listed in my tableview. 我有一个表视图,想将childChange函数添加到我的表视图中,但是我尝试这样做,而不是更新Child,我的Tableview添加了另一行并带有更改的子项,因此我有一个旧值行和新的更新行在我的表格视图中列出。
in my viewdidload I have defined my firebase reference and added two functions: 在我的viewdidload中,我定义了firebase参考并添加了两个功能:
ref = Database.database().reference().child("paris")
fetchBars()
refreshBars()
and have defined below viewdidload two functions: 并在下面的viewdidload中定义了两个函数:
func fetchBars(){
ref.observe(.childAdded, with: { (snapshot) in
guard let bar = Bar.bar(from: snapshot) else {return}
self.bars.append(bar)
self.tableView.reloadData()
})
}
func refreshBars(){
ref.observe(.childChanged, with: { (snapshot) in
guard let bar = Bar.bar(from: snapshot) else {return}
self.bars.append(bar)
self.tableView.reloadData()
})
}
For me it would be helpful if I could make an observer of ChildAdded and ChildChange in the single function. 对我来说,如果可以在单个函数中观察ChildAdded和ChildChange会很有帮助。 Please help me and thank you in advance. 请帮助我,谢谢你。
CellforRow: CellforRow:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RestoCell", for: indexPath) as! ViewControllerCell
let bar = bars[indexPath.row]
cell.RestName.text = bar.barName
cell.RestAddress.text = bar.barAddress
cell.RestImage.sd_setImage(with: URL(string: bar.barMainImage))
cell.percentLabel.text = bar.percentage
return cell
}
You need to update the row instead of adding a new one, first of all, you need to add a unique id for the Bar class to use it to get the index of the row, it will be something like this: 您需要更新该行而不是添加一个新行,首先,您需要为Bar类添加一个唯一的ID,以使用它来获取该行的索引,这将是这样的:
func refreshBars(){
ref.observe(.childChanged, with: { (snapshot) in
guard let bar = Bar.bar(from: snapshot) else {return}
// you need to find the index of the bar
let index = self.bars.index(where: { otherbar in bar.id == bar.id })!
// remove the old one
self.bars.remove(at: index)
// add the new one
self.bars.insert(bar, at: index)
// reload the row with fade animation
self.tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .fade)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.