Kevin DiTraglia Kevin DiTraglia - 1 year ago 223
Objective-C Question

cellForItemAtIndexPath returns nil after force scrolling to make it visible

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

call will return nil, causing the rest of my logic to fail.

[_myView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index

//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]];

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download