Friday 18 March 2016

Custom layout for Collection View

UICollectionView provides a way in which we can arrange our data in a grid . Some times we may encounter a problem where we want to design the grid in our way , for example we may want to show the layout of the collection view cell based on the content size of the data we want to display in the collection view. In this way we have to define our custom layout for the each cell based on the content size of the data.


Collection view layouts are subclasses of  the abstract UICollectionViewLayout class. They define the visual attribute of each item in your collection view.

The individual attributes are instances of  UICollectionViewLayoutAttributes and contain the properties of each item in your collection view, such as the frame or opacity of the item .

To customize the layout of the the collection view we have to understand how collection view and layout object works together. Collection view layout process is a collaboration between collection view and the layout object.
When collection view needs some information about layout, it asks your layout object to provide it by calling certain methods in a specific order:

1) prepareLayout
2) collectionViewContentSize
3) layoutAttributesForElementsInRect:

Your layout subclass must implement above mentioned methods:

1) prepareLayout(): It is called when a layout operation is to take place. Here we make calculations to define the collection view size and and the position of the items.

2) collectionViewContentSize(): In this method we return the  height and width of the entire collection view.

3) layoutAttributesForElementInRect(_:) In this method we return  the layout attributes for all the items in a given rect as  UICollectionViewLayoutAttributes .

No comments:

Post a Comment