我正在实现自定义流布局.它有两种主要的重写方法来确定单元格的布局:layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath.
在我的代码中,调用layoutAttributesForElementsInRect,但是layoutAttributesForItemAtIndexPath不是.什么决定哪个被叫? layoutAttributesForItemAtIndexPath在哪里被调用?
解决方法
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
}