UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath

Gau*_*rma 11 objective-c ios uicollectionview uicollectionviewlayout uicollectionviewdelegate

我正在实现自定义流布局.它有两种主要的覆盖方法来确定细胞的位置:layoutAttributesForElementsInRectlayoutAttributesForItemAtIndexPath.

在我的代码中,layoutAttributesForElementsInRect被称为,但layoutAttributesForItemAtIndexPath不是.什么决定了什么叫?layoutAttributesForItemAtIndexPath被叫哪里?

Rob*_*ert 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
}
Run Code Online (Sandbox Code Playgroud)

  • @ moonman239` [super layoutAttributesForElementsInRect]`在`UICollectionViewFlowLayout`的子类上使用时返回有效的布局属性.当在`UICollectionViewLayout`的自定义子类上使用时,它返回`nil`.如果您基于`UICollectionViewLayout`编写自己的布局,则可以使用`[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:]`创建空白布局属性. (4认同)
  • `UICollectionViewLayoutAttributes`具有`indexPath`属性. (3认同)