2016-08-30 36 views
0

我在排序字典中的某個鍵時遇到了問題。關鍵是基本上是一個時間戳,我正在嘗試排序我桌子頂部的最新帖子。我不知道是否必須重新加載表格,因爲我在另一個循環內有一個循環,或者如果我在cellForRowAtIndexPath中的排序不正確。我看到數據,並且正在通過第一個循環(對於Feed中的項目)進行排序。我無法完成整個循環,然後按字典中的時間戳鍵排序。任何幫助是極大的讚賞。在字典中對時間戳進行排序TableView

var posts = [Post]() 

func feedPosts(){ 
    for items in feed{ 
     let feedId = items["id"] as! String 
     ref.queryOrderedByChild("myFeed").queryEqualToValue(「\(feedId)」).observeEventType(.Value, withBlock: { snapshot in 
      if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { 
       for snap in snapshot { 
        if let postDict = snap.value as? Dictionary<String, AnyObject> { 
         let key = snap.key 
         let post = Post(postKey: key, postData: postDict) 
         self.posts.insert(post, atIndex: 0) 
        } 
       } 
      } 
      self.tableView.reloadData() 
     }) 
    } 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let post = posts.sort({$0.postedDate > $1.postedDate})[indexPath.row] 

    let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? FeedPostCell 
    cell.configureCell(post) 
    return cell 
} 

恢復單元

class FeedPostCell: UITableViewCell { 

    @IBOutlet var feedTxt: UITextView! 
    var post: Post! 

    func configureCell(post: Post, img: UIImage? = nil) { 
    self.post = post 
    self.feedTxt.text = post.feedTxt 
    if img != nil { 
     self.postImg.image = img 
    } 
    } 
} 

數據結構

-posts 
    - postKey 
    - myFeed : "123" 
    - timestamp: 1472596316060 
    - feedTxt: "Here is my feed text" 
+0

你的時間戳字符串是什麼樣的? –

+0

不是一個解決方案,但是你應該在調用'tableView.reloadData()'之前對你的帖子進行排序。這樣,每次調用'cellForRowAtIndexPath'時,數組都不會被排序。 – Carter

+0

@JosephQuigley我的時間戳以毫秒爲單位。我使用firebase.database.ServerValue.TIMESTAMP – kelsheikh

回答

0

你的職位應進行排序,你希望他們的方式,但它看起來像你並沒有使用什麼到細胞。嘗試是這樣的:

cell.postTextLabel.text = post["postStringHere"] 

cell.postTextLabel是一個UILabel將包含從您的文章對象的文本。

+0

大概這就是'cell.configureCell(post)'調用的作用。 OP應編輯他的帖子以提供該代碼,以及他的「Post」對象的結構。 –

+0

配置單元格當我問的時候並沒有在問題的修訂版本中,但知道它的身體確實會有所幫助 –

+0

Oh lordy。那現在不會工作得很好嗎? –

相關問題