UICollectionView单元格仅在第二次调用reloadData后显示

See*_*ode 8 ios uicollectionview swift

我可能正在做一些非常愚蠢的事情,但我无法弄清楚我的生活是怎么回事......

我想要做的很简单.我UICollectionView依赖于我从服务器加载的数据.从服务器获取并设置数据后,我调用reloadData()集合视图.当我这样做时,numberOfItemsInSection被调用正确的计数,但cellForItemAt除非我reloadData()再次呼叫(甚至不需要延迟),否则永远不会被调用.

这是一般性的想法(虽然我意识到这可能与其他地方的某些竞争有关,但也许这足以启动对话):

class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    var data = [DataModel]()

    override func viewDidLoad() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "MyCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")
        getData()
    }

    func getData() {
        someAsyncMethodToGetData() { (data) in
            // Using CloudKit so I think this is necessary, but tried it with and without
            DispatchQueue.main.async {
                self.data = data
                self.collectionView.reloadData()
                // This is the only way to get cells to render and for cellForItemAt to be called after data is loaded
                self.collectionView.reloadData()
            }
        }

    // Gets called initially AND after reloadData is called in the data completion closure. First time is 0, next time is number of DataModel objects
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    // Only gets called initially (unless I call reloadData() twice)
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = feedCollectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else {
            return UICollectionViewCell()
        }

        // Configure the cell with data...

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

所以这里有一些我已经尝试过的东西:

  • reloadData()在主线程上调用了double sure (添加了一个符号断点并调用Thread.isMainThread验证)
  • 移动reloadData()到按钮操作以消除任何线程问题的可能性 - 仍然必须单击按钮两次以显示单元格
  • performBatchUpdates根据我遇到的其他一些SO解决方案进行更新
  • 添加setNeedsLayout和setNeedsDisplay(不确定为什么在这种情况下这是必要的,但我确实是出于绝望而尝试的.

有什么建议?

更新1

好吧,我想我发现了这个问题,但我想了解最好的解决方法.通过调用显示reloadData,集合视图将仅重新加载已经可见的单元格.在getData()调用之前,我在上面修改了一些代码以返回1个单元格.当getData()然后调用reloadData()一个1个细胞得到更新(但如果有数据阵列中10个项目,它仍然会只[重新]来显示1个细胞).我认为这是有道理的,因为reloadData()只重新加载可见单元格,但是当数组的长度发生变化并且屏幕上仍有空间显示时,这必然是一个常见问题.此外,为什么reloadData()两次调用解决问题并显示从未见过的单元格?

这是我上面的代码更简单的版本,删除整个"从服务器获取数据"的想法,并用简单的延迟替换.

Rom*_*uba 10

事情是UICollectionViewFlowLayout在更改项目数后没有正确无效.所以collectionView.contentSize还是老了.你需要做点什么

self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()
Run Code Online (Sandbox Code Playgroud)

这将告诉布局重新计算新数据源.

  • 你好!我遇到了同样的问题,但即使在添加 invalidateLayout() 后仍然发生同样的事情。我的课上有与上面相同的代码。 (3认同)