[英]UICollectionViewFlowLayout's layoutAttributesForItemAtIndexPath returns nil when called “too early”
我的设置:具有流布局的标准UICollectionView; 数据源设置为我的控制器。 在xib文件中按常规配置布局。 当我尝试通过Controller的viewDidLoad方法中的layoutAttributesForItemAtIndexPath:访问单元格的布局属性时,如下所示:
NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0]]);
输出是
"LayoutAttribute: (null)"
即使布局具有为我提供正确布局属性所需的所有信息。 它仍然无法在viewWillAppear:中工作,但是“神奇地”开始在viewDidAppear中工作:
"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"
我发现了使它工作的非常奇怪的方法。 我只是在请求布局属性之前访问collectionViewContentSize:
NSLog(@"Layout content size: %@", NSStringFromCGSize(self.collectionView.collectionViewLayout.collectionViewContentSize));
NSLog(@"LayoutAttribute: %@", [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath: [NSIndexPath indexPathForRow:0 inSection:0]]);
一直如预期的那样输出:
"Layout content size: {768, 50}"
"LayoutAttribute: <UICollectionViewLayoutAttributes: 0x8c4f710> index path: (<NSIndexPath 0x8c48be0> 2 indexes [0, 0]); frame = (0 0; 50 50);"
这里发生了什么? 我假设访问内容大小会触发布局中的某些内容,但是有人知道是否有适当的方法来执行此操作吗? 还是这只是一个令人讨厌的错误?
layoutAttributesForItemAtIndexPath:
的文档说,如果该索引路径中没有任何项目,则仅返回nil
。 在调用layoutAttributesForItemAtIndexPath:
之前,您是否未在集合视图上调用reloadData
?
另一个常见问题是调用链中的某些中间对象为nil
。 也许collectionView或collectionView.collectionViewLayout nil
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.