AFAIK, the reason that cause UICollectionViewLayout restart layout process are:
UICollectionView
's frame changeUICollectionView
reload dataUICollectionView
insert/delete itemsUICollectionView
's bound change (if shouldInvalidateLayoutForBoundsChange return YES)In my custom layout implementation, I want to change the UICollectionViewLayoutAttributes
of certain items as the bound changes (stick header to the top like UITableView
, animate item in/out .etc).
Problem is that for whatever reason it is, the UICollectionView always call its layout object's prepareLayout
method (which contains heavy layout computation) and that make jerky scrolling.
I'm going for the solution that opt out the layout computation if the reason is UICollectionView
's bound change.
How to check what reason the prepareLayout
call?
I set a flag in shouldInvalidateLayoutForBoundsChange:
so I know not to recalculate everything when that happens (on every frame...).
You can set another flag when prepareForAnimatedBoundsChange:
is called, which happens when new items are inserted or when the bounds of the collection view change. You can then know if the bounds were changed because of scrolling or because of resize thanks to the flag you set in shouldInvalidateLayoutForBoundsChange:
.
However, you should not have to worry too much of why you have to prepare the layout, since you should recalculate it fully in most cases anyways. In my project the only case where I do something differently in prepareLayout
is when the invalidation was caused by scrolling.