OGeek|极客世界-中国程序员成长平台

标题: ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:30
标题: ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目

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

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

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

这是一个显示问题的最小片段。

   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 位于可见项数组中。但事实并非如此。在项目被视为可见之前是否必须发生某些事件?我错过了什么?



Best Answer-推荐答案


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 .

关于ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41508501/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4