2017-07-11 37 views
0

這是問題所在。收集查看時排序未排序的數組

創建一個json對象數組後,我對它們進行排序。當我加載控制器時,集合視圖會閃爍未排序的數組,然後顯示已排序的數組(請參閱下面的演示)。

CollectionView Flicker Problem Demo

我試過的要對這個問題的一些方法。

  1. GCD首先完成排序,然後重新加載收集視圖。

  2. GCD刪除數組,然後繼續請求。

  3. Dispatch異步排序和集合視圖重新加載。

這裏是我的代碼

ref.observeSingleEvent(of: .value, with: { (snapshot) in 

     self.collectionView?.refreshControl?.endRefreshing() 

     guard let dictionaries = snapshot.value as? [String: Any] else { return } 

     dictionaries.forEach({ (key, value) in 
      guard let dictionary = value as? [String: Any] else { return } 

      var post = Post(user: user, dictionary: dictionary) 
      post.id = key 

      self.posts.sort(by: { (p1, p2) -> Bool in 
       return p1.creationDate.compare(p2.creationDate) == .orderedDescending 
      }) 
      self.posts.append(post) 
      self.collectionView?.reloadData() 

     }, withCancel: { (err) in 
      print("Failed to fetch like info for post:", err) 
     }) 
    }) 

我真的不知道自己還能做些什麼。任何想法?

回答

1

在每次更新之後,您正在告訴集合視圖更新其內容(通過調用reloadData())。這會導致閃爍。爲防止出現這種情況,只有在完成所有更新後才告訴集合視圖進行更新:

ref.observeSingleEvent(of: .value, with: { (snapshot) in 

    self.collectionView?.refreshControl?.endRefreshing() 

    guard let dictionaries = snapshot.value as? [String: Any] else { return } 

    dictionaries.forEach({ (key, value) in 
     guard let dictionary = value as? [String: Any] else { return } 

     var post = Post(user: user, dictionary: dictionary) 
     post.id = key 

     self.posts.sort(by: { (p1, p2) -> Bool in 
      return p1.creationDate.compare(p2.creationDate) == .orderedDescending 
     }) 
     self.posts.append(post) 

    }, withCancel: { (err) in 
     print("Failed to fetch like info for post:", err) 
    }) 
    self.collectionView?.reloadData() 
}) 
+0

解決了這個問題!我也有一個方法,在獲取請求中有一個獲取請求..同樣的問題依然存在..任何想法我可以解決這個問題? – user7045671