Overview of the General Layout Process

Overview of the Layout Process with Self Sizing Cells

Self Sizing Cells Layout — func by func

After the initial attributes are obtained for the elements in the initially visible rect, the self sizing process begins. The collection view asks your data source for the view at the index path of the first of these attributes. Then it asks this view for “preferred attributes fitting” these attributes.

UIReusableView (Cell, Supplementary or Decoration view): preferredLayoutAttributesFitting(_:)

UICollectionViewLayout: shouldInvalidateLayout(forPreferredLayoutAttributes:withOriginalAttributes:)

Your collection view then takes the preferred attributes returned by your view and asks the layout if it needs to invalidate for them. The answer is almost always yes if the size in the preferred attributes is different from the size in the original attributes: a new layout will need to be calculated to account for the new size.

UICollectionViewLayout: invalidationContext(forPreferredLayoutAttributes:withOriginalAttributes:)

Now your collection view asks for an invalidation context for these preferred attributes. There are 3 things that need to happen here.

UICollectionViewLayout: invalidateLayout(with:)

UICollectionViewLayout: prepare()

Now when you precalculate your layout data, you must take the preferred attributes information you stored earlier into account. I suggest doing this naively first: just rebuild the whole layout using the preferred attributes. Once you have that working and tested, start optimising. Part 3 will have more detail around optimisations here.

UICollectionViewLayout: layoutAttributesFor...

Now the collection view asks for the new attributes. It will usually call one of the at: methods for the index path that provided preferred attributes, but it may request the whole rect again.

UIReuseableView: preferredLayoutAttributesFitting(_:)

End of Part 1

Max Clarke

Tech Lead,Brisbane

Max Clarke

Tech Lead,Brisbane