和layoutAttributesForItemAtIndexP

和layoutAttributesForItemAtIndexP

我正在实现自定义流布局。它有2种主要的方法可以覆盖以确定单元格的位置:layoutAttributesForElementsInRectlayoutAttributesForItemAtIndexPath

在我的代码中,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
}

关于ios - UICollectionViewLayout layoutAttributesForElementsInRect和layoutAttributesForItemAtIndexPath,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24490841/

10-09 02:41