【问题标题】:Sort table view cells by detail number value from Firebase按 Firebase 中的详细数字值对表格视图单元格进行排序
【发布时间】:2017-02-13 05:20:16
【问题描述】:

如何根据详细文本标签中的值对表格视图单元格进行排序?我在 Firebase 中有名称和分数,我要提取这些名称和分数,并希望按分数从高到低的顺序显示。

目前,我正在检索 Firebase 名称和值,但它们只是按主文本字段中名称的字母顺序显示。我尝试使用 {$0.scoreTotal > $1.scoreTotal} 按分数值排序,并使用 queryOrdered(byChild: "scoreTotal") 对 Firebase 数据进行排序,但似乎都不起作用。

这是代码的表格视图部分:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CellMale", for: indexPath as IndexPath)

    let comp = comps[indexPath.row]
    self.comps.sorted(by: {$0.scoreTotal > $1.scoreTotal})


    let dbRef1 = FIRDatabase.database().reference().child("Live Scoring Male/\(String(describing: comp.name!))/scoreTotal")

    dbRef1.queryOrdered(byChild: "scoreTotal").observe(FIRDataEventType.value, with: { (snapshot) in

        let scoreTotal = snapshot.value as! Double

        cell.detailTextLabel?.text = String(scoreTotal)

    })

    cell.textLabel?.text = comp.name

    return cell

} 

【问题讨论】:

  • 我可以知道你为什么在cellForRowAtIndexPath中调用数据库查询吗?
  • @CodeChanger 我正在学习,所以我非常感谢你如何组织这个的建议。我只需要 Firebase 值作为表格视图单元格中的 detailTextLabel ,所以我把它放在那里。您会在 viewDIdLoad 中加载 Firebase 值,然后将这些值加载到每个单元格中吗?

标签: ios sorting firebase firebase-realtime-database tableview


【解决方案1】:

第一件事是永远不要将任何服务调用到cellForRowAtIndex 中,并在需要时调用它,例如在我们加载视图时使用viewDidLoad() 方法将任何数据加载到该控制器中。

所以将上述方法调用到viewDidLoad 并关于对您的数据进行排序

使用 FireBase 排序,如下所示:

let ref = FIRDatabase.database().reference(fromURL: <FIREBASE_URL>).child("topics")
        let query = ref.queryOrdered(byChild: "scores")
        query.observe(.value, with: { (snapshot) in
            for childSnapshot in snapshot.children {
                print(childSnapshot)
            }
        })

将其捕获到本地数组或字典中,并通过 reloadData() 方法在您的 TableView 中使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多