Objective c UICollectionViewFlowLayout&x27;s layoutAttributesForItemAtIndexPath在调用“时返回nil”;“太早了”;

Objective c UICollectionViewFlowLayout&x27;s layoutAttributesForItemAtIndexPath在调用“时返回nil”;“太早了”;,objective-c,uicollectionview,uicollectionviewlayout,Objective C,Uicollectionview,Uicollectionviewlayout,我的设置: 具有流布局的标准UICollectionView;数据源已设置为我的控制器。 布局在xib文件中按常规配置。 当我尝试通过控制器的viewDidLoad方法中的layoutAttributesForItemAtIndexPath:访问单元格的布局属性时,如下所示: NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NS

我的设置: 具有流布局的标准UICollectionView;数据源已设置为我的控制器。 布局在xib文件中按常规配置。 当我尝试通过控制器的viewDidLoad方法中的layoutAttributesForItemAtIndexPath:访问单元格的布局属性时,如下所示:

NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0]]);
输出是

"LayoutAttribute: (null)"
即使布局包含提供正确布局属性所需的所有信息。 它仍然无法在ViewWillDisplay:中工作,但它“神奇地”开始在ViewDidDisplay中工作:

"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"
正如预期的那样,输出始终是:

"Layout content size: {768, 50}"
"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"
“版面内容大小:{768,50}”
LayoutAttribute:索引路径:(2个索引[0,0]);帧=(0;50)

这是怎么回事?我假设访问内容大小会触发布局中的某些内容,但是有人知道是否有正确的方法来实现这一点吗?或者这只是一个恼人的bug?

layoutAttributesForItemAtIndexPath:的文档中说,如果索引路径中没有项目,它只返回
nil
。在调用
layouttributesforItemAtIndexPath:
之前,您可能没有在集合视图上调用
reloadData

另一个常见问题是调用链中的某个中间对象是
nil
。可能collectionView或collectionView.collectionViewLayout是
nil

"Layout content size: {768, 50}"
"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"