【问题标题】:collectionView.indexPathsForVisibleItems doesn't list items I know are visiblecollectionView.indexPathsForVisibleItems 没有列出我知道可见的项目
【发布时间】:2017-05-21 09:09:23
【问题描述】:

我有一个UICollectionView,它显示单元格,其中部分包含我需要从服务器获取的图像。在cellForItemAt 中,我检查我的缓存以查看图像是否可用,如果不可用,则调用方法下载图像。

在该方法中,我异步加载图像。下载图像后,我检查与该图像关联的 indexPath 是否可见。如果是这样,我会调用 reloadItems 来更新显示。

问题是我可以在模拟器上看到空单元格,但它不是在可见单元格数组中。

这是一个显示问题的最小 sn-p。

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell: ThumbCell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseId, for: indexPath) as! PosterThumbCell


    print("cellforItemAt: \(indexPath)")
    print("visibleItems: \(collectionView.indexPathsForVisibleItems)")

    ...
    return cell
}

现在我希望 indexPath 位于可见项数组中。但事实并非如此。在项目被视为可见之前是否必须发生某些事件?我错过了什么?

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 由 collectionView 调用以获取它将显示的单元格。因此,如果您在从此函数返回之前打印可见单元格,则新出列的单元格将不在数组中。

    要对此进行测试,请添加一个测试按钮并将您的打印从该数据源函数移至按钮的处理程序。显示单元格后点击按钮,它将在数组中。

    我不知道你的下载方法是什么样的,但你的骨架应该是这样的:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: ThumbCell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseId, for: indexPath) as! PosterThumbCell
    
    
        if let image = self.getImage(for: indexPath) {
            cell.image = image
        } else {
            weak var weakCell = cell
            self.loadImageFromServer(for: indexPath) { (image) in
                // Should check that the cell is still used for the same IndexPath
                weakCell?.image = image
            }    
        }
        return cell
    }
    

    如果已经下载,则分配图像,否则下载并在完成时分配。请注意,您在开始请求时使用的单元格可以在下载结束时重新用于其他 indexPath。有关更多详细信息,您应该查看此answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多