ios - 如何在 tableView 上反射(reflect) childChanges - IOS Swift Firebase

标签 ios swift firebase firebase-realtime-database tableview

我有一个 TableView ,想将 childChange 函数添加到我的 TableView 中,但我尝试这样做,而不是更新子项,我的 TableView 添加了另一行包含已更改的子项,所以我有一个旧值行和我的表格 View 中列出了新更新的行。

在我的 viewdidload 中,我定义了我的 firebase 引用并添加了两个函数:

        ref = Database.database().reference().child("paris")
    fetchBars()
    refreshBars()

下面定义了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()
    })
}

对我来说,如果我可以在单个函数中创建 ChildAdded 和 ChildChange 的观察者,将会很有帮助。 请帮助我并提前感谢您。

行单元格:

    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
}

最佳答案

您需要更新行而不是添加新行,首先,您需要为 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)
    })
}

关于ios - 如何在 tableView 上反射(reflect) childChanges - IOS Swift Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48690575/

相关文章:

c# - Xamarin Forms iOS 应用程序检测到 "Return"已按下

Swift - 找出哪个表格 View 单元格占据了大部分屏幕

json - 在加载 UI 之前执行代码

angularfire2 找不到模块 'firebase/app'

swift - Firebase 数据库 - fatal error : Unexpectedly found nil while unwrapping an Optional value

ios - 安装失败 : Invalid Argument -iOS Extension

ios - 缺少 iOS 分发签名身份/"Certificate has an invalid issuer"

firebase批量更新和onWrite触发同步

ios - 更改 EXIF 数据以正确识别 iPhone

swift - 比较 Swift 类层次结构中的协议(protocol)