本文介绍了在强制滚动后,cellForItemAtIndexPath返回nil以使其可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试着编写一些代码来将集合视图滚动到某个索引,然后拉出对单元格的引用并做一些逻辑。但是我注意到如果在滚动之前该单元格当前不可见, cellForItemAtIndexPath 调用将返回nil,导致我的其余逻辑失败。

So I am trying to write some code that scrolls a collection view to a certain index, then pulls a reference to the cell and does some logic. However I've noticed if that cell wasn't presently visible prior to the scroll, the cellForItemAtIndexPath call will return nil, causing the rest of my logic to fail.

[_myView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index
                                                     inSection:0]
                atScrollPosition:UICollectionViewScrollPositionTop
                        animated:NO];

//Tried with and without this line, thinking maybe this would trigger a redraw
[_myView reloadData];

//returns nil if cell was off-screen before scroll
UICollectionViewCell *cell =
  [_myView cellForItemAtIndexPath:
    [NSIndexPath indexPathForItem:index inSection:0]];

我是否需要调用其他方法来导致 cellForItemAtIndexPath 为一个突然进入视野的单元格返回一些东西,因为它前面的滚动?

Is there some other method I have to call to cause the cellForItemAtIndexPath to return something for a cell that suddenly came into view as a result of the scroll immediately preceding it?

推荐答案

根据你的评论,这听起来像你最终的细胞框架。不依赖于单元格存在的方法是询问集合视图的布局:

Based on your comments, it sounds like what you're ultimately after is the cell's frame. The way to do that without relying on existence of the cell is to ask the collection view's layout:

NSIndexPath *indexPath = ...;
UICollectionViewLayoutAttributes *pose = [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
CGRect frame = pose.frame;

这篇关于在强制滚动后,cellForItemAtIndexPath返回nil以使其可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:01