0
votes

I'm a new iOS developer.

Recently I'm learning UICollectionView and I'm trying to subclass the UICollectionViewLayout.

I have to implement the method

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect

Question

I have no idea where did this rect come from? and in which scenario will this rect be passed to me ?

PS. I think this method might be more easy to understand

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path

Because the indexPath is limited and finite and configure the cell in the particular indexPath is reasonable.

But the rect might be infinite and I have no idea where this rect came from.

1

1 Answers

1
votes

When creating a layout subclass you must override both methods.

The layoutAttributesForItemAtIndexPath tells the collection-view what are the layout attributes for a cell at a specific index-path. You must only use it for cells.

The layoutAttributesForElementsInRect gets called by the system with a rectangle which contains all "visual elements" to be displayed in it - cells, supplementary or decoration views. Think of it as the part of the collection-view that's about to be displayed. It tells the collection-view which attributes are contained in the rectangle, so it can create the corresponding views.

Basically, you can do all your layout attribute calculations (frame, transforms, etc.) inside these functions, or you can prepare all attributes in advance (you can do that in the prepareLayout method) and just return the correct cached layout attributes.