UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath

时间:2014-06-30 13:05:33

标签: ios objective-c uicollectionview uicollectionviewlayout uicollectionviewdelegate

我正在实施自定义流程布局。它有两种主要的覆盖方法来确定单元格的位置:layoutAttributesForElementsInRectlayoutAttributesForItemAtIndexPath

在我的代码中,layoutAttributesForElementsInRect被调用,但layoutAttributesForItemAtIndexPath不是。什么决定了什么叫? layoutAttributesForItemAtIndexPath在哪里被召唤?

1 个答案:

答案 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
}