【问题标题】:UICollectionViewLayout layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPathUICollectionViewLayout layoutAttributesForElementsInRect 和 layoutAttributesForItemAtIndexPath
【发布时间】:2014-06-30 13:05:32
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c uicollectionview uicollectionviewlayout uicollectionviewdelegate


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 如果我需要索引路径来确定属性的rect属性怎么办?我无法将索引路径传递给修改函数。
    • A UICollectionViewLayoutAttributes 具有 indexPath 属性。
    • @Robert [super layoutAttributesForElementsInRect] 不返回 nil 吗?这是我从 Apple 文档中得到的印象。
    • @moonman239 [super layoutAttributesForElementsInRect]UICollectionViewFlowLayout 的子类上使用时返回有效的布局属性。当用于UICollectionViewLayout 的自定义子类时,它返回nil。如果您基于UICollectionViewLayout 编写自己的布局,则可以使用[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:] 创建空白布局属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多