我正在实施自定义流程布局。它有两种主要的覆盖方法来确定单元格的位置:layoutAttributesForElementsInRect
和layoutAttributesForItemAtIndexPath
。
在我的代码中,layoutAttributesForElementsInRect
被调用,但layoutAttributesForItemAtIndexPath
不是。什么决定了什么叫? layoutAttributesForItemAtIndexPath
在哪里被召唤?
答案 0 :(得分:19)
layoutAttributesForElementsInRect:
并非必须致电layoutAttributesForItemAtIndexPath:
。
实际上,如果你继承UICollectionViewFlowLayout
,流布局将准备布局并缓存结果属性。因此,当调用layoutAttributesForElementsInRect:
时,它不会询问layoutAttributesForItemAtIndexPath:
,而只是使用缓存的值。
如果您想确保始终根据布局修改布局属性,请为layoutAttributesForElementsInRect:
和layoutAttributesForItemAtIndexPath:
实施修改器:
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *attributesInRect = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes *cellAttributes in attributesInRect) {
[self modifyLayoutAttributes:cellAttributes];
}
return attributesInRect;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attributes = [super layoutAttributesForItemAtIndexPath:indexPath];
[self modifyLayoutAttributes:attributes];
return attributes;
}
- (void)modifyLayoutAttributes:(UICollectionViewLayoutAttributes *)attributes
{
// Adjust the standard properties size, center, transform etc.
// Or subclass UICollectionViewLayoutAttributes and add additional attributes.
// Note, that a subclass will require you to override copyWithZone and isEqual.
// And you'll need to tell your layout to use your subclass in +(Class)layoutAttributesClass
}