11

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

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

4

1 回答 1

22

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
}
于 2014-08-29T10:53:14.223 回答