【问题标题】:CollectionView flickers unsorted array when sorting排序时CollectionView闪烁未排序的数组
【发布时间】:2017-07-11 01:07:25
【问题描述】:

这就是问题所在。

创建一个 json 对象数组后,我对它们进行排序。当我加载控制器时,集合视图会闪烁未排序的数组,然后呈现已排序的数组(请参阅下面的演示)。

CollectionView Flicker Problem Demo

我尝试了几种方法来解决这个问题。

  1. GCD 先完成排序,然后重新加载集合视图。

  2. GCD 删除阵列,然后继续请求。

  3. 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)
        })
    })

我真的不知道还能做什么......有什么想法吗?

【问题讨论】:

    标签: swift sorting firebase firebase-realtime-database uicollectionview


    【解决方案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()
    })
    

    【讨论】:

    • 这解决了问题!我还有一个在获取请求中包含获取请求的方法。同样的问题仍然存在。知道如何解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 2017-06-21
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多