Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewLayout layoutAttributesForElementsInRect and layoutAttributesForItemAtIndexPath

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?

like image 914
Gaurav Sharma Avatar asked Jun 30 '14 13:06

Gaurav Sharma


1 Answers

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
}
like image 188
Robert Avatar answered Nov 04 '22 01:11

Robert