UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath
我正在实现一个自定义stream布局。 它有2个主要的方法来重写确定单元格的位置: layoutAttributesForElementsInRect
和layoutAttributesForItemAtIndexPath
。
在我的代码中, layoutAttributesForElementsInRect
被调用,但是layoutAttributesForItemAtIndexPath
不是。 什么决定哪些被调用? layoutAttributesForItemAtIndexPath
在哪里被调用?
layoutAttributesForElementsInRect:
不一定会调用layoutAttributesForItemAtIndexPath:
事实上,如果你UICollectionViewFlowLayout
,stream布局将准备布局并caching结果属性。 所以,当layoutAttributesForElementsInRect:
被调用时,它不会问layoutAttributesForItemAtIndexPath:
只是使用caching的值。
如果要确保布局属性始终根据布局进行修改,请为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 }