作者:潘佳锐_340 | 来源:互联网 | 2023-05-17 05:46
WhenIloadthefollowingFirebaseDatabasedataintomytableView,thedataissortedinascending
When I load the following Firebase Database data into my tableView, the data is sorted in ascending order by date. How can I order this by descending (show the newest post at the top)?
当我将以下Firebase数据库数据加载到我的tableView中时,数据按日期按升序排序。如何通过降序(在顶部显示最新的帖子)来订购?
Query in Xcode:
在Xcode中查询:
let ref = self.rootRef.child("posts").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
JSON export:
JSON导出:
"posts" : {
"-KMFYKt7rmfZINetx1hF" : {
"date" : "07/09/16 12:46 PM",
"postedBy" : "sJUCytVIWmX7CgmrypqNai8vGBg2",
"status" : "test"
},
"-KMFYZeJmgvmnqZ4OhT_" : {
"date" : "07/09/16 12:47 PM",
"postedBy" : "sJUCytVIWmX7CgmrypqNai8vGBg2",
"status" : "test"
},
Thanks!!
谢谢!!
EDIT: Below code is the entire solution thanks to Bawpotter
编辑:感谢Bawpotter,代码是完整的解决方案
Updated query:
更新的查询:
let ref = self.rootRef.child("posts").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
let post = Post.init(key: snapshot.key, date: snapshot.value!["date"] as! String, postedBy: snapshot.value!["postedBy"] as! String, status: snapshot.value!["status"] as! String)
self.posts.append(post)
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.posts.count-1, inSection: 0)], withRowAnimation: .Automatic)
tableView cellForRowAtIndexPath
tableView cellForRowAtIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! PostCell
self.posts.sortInPlace({$0.date > $1.date})
self.tableView.reloadData()
Post.swift:
Post.swift:
import UIKit
class Post {
var key: String
var date: String
var postedBy: String
var status: String
init(key: String, date: String, postedBy: String, status: String){
self.key = key
self.date = date
self.postedBy = postedBy
self.status = status
}
}
2 个解决方案