菜鸟教程小白 发表于 2022-12-11 18:30:43

ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目


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

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

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

<p>这是一个显示问题的最小片段。</p>

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


    print(&#34;cellforItemAt: \(indexPath)&#34;)
    print(&#34;visibleItems: \(collectionView.indexPathsForVisibleItems)&#34;)

    ...
    return cell
}
</code></pre>

<p>现在我希望 indexPath 位于可见项数组中。但事实并非如此。在项目被视为可见之前是否必须发生某些事件?我错过了什么?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p><code>collectionView(_collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell</code> 被collectionView 调用以获取它将显示的单元格。因此,如果您在从此函数返回之前打印可见单元格,则新出列的单元格将不在数组中。</p>

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

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

<pre><code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; 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
}
</code></pre>

<p>如果已下载,则分配图像,否则下载并在完成时分配。请注意,您在开始请求时使用的单元格可以在下载结束时重新用于其他 indexPath。有关更多详细信息,您应该查看此 <a href="https://stackoverflow.com/a/16663759/3769338" rel="noreferrer noopener nofollow">answer</a> .</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/41508501/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/41508501/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - collectionView.indexPathsForVisibleItems 没有列出我知道可见的项目