cellForItemAtIndexPath 在强制滚动以使其可见后返回 nil [英] cellForItemAtIndexPath returns nil after force scrolling to make it visible

查看:38
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆