这是问题所在。
创建json对象数组后,我对它们进行排序。当我加载控制器时,集合视图会闪烁未排序的数组,然后呈现排序的数组(请参阅下面的演示)。
CollectionView Flicker Problem Demo
我已经尝试了几种解决这个问题的方法。
GCD首先完成排序,然后重新加载集合视图。
GCD删除数组,然后继续请求。
Dispatch Async排序和集合视图重新加载。
这是我的代码
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)
})
})
我真的不知道还能做什么......有什么想法吗?
答案 0 :(得分: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()
})