UICollectionViewLayout layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPath

↘锁芯ラ 提交于 2020-01-11 00:08:33

问题


I'm implementing a custom flow layout. It has 2 main methods for overriding to determine placement of cells: layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPath.

In my code, layoutAttributesForElementsInRect is called, but layoutAttributesForItemAtIndexPath isn't. What determines which gets called? Where does layoutAttributesForItemAtIndexPath get called?


回答1:


layoutAttributesForElementsInRect: doesn't necessarily call layoutAttributesForItemAtIndexPath:.

In fact, if you subclass UICollectionViewFlowLayout, the flow layout will prepare the layout and cache the resulting attributes. So, when layoutAttributesForElementsInRect: is called, it won't ask layoutAttributesForItemAtIndexPath:, but just uses the cached values.

If you want to ensure that the layout attributes are always modified according to your layout, implement a modifier for both layoutAttributesForElementsInRect: and 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
}


来源:https://stackoverflow.com/questions/24490841/uicollectionviewlayout-layoutattributesforelementsinrect-and-layoutattributesfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!