UICollectionViewLayout’s responsibility is to define layout: all the cell locations and sizes. It acts like a data source object which provides layout related information to the collection view. Collection view then uses that information for creating cells and placing them on screen. This time we’ll take a look on how to create a custom circle shaped layout.
Creating UICollectionViewLayout subclass
First step for creating a custom layout is to create UICollectionViewLayout subclass. Then we need to define the size of the layout. In this simple case, all the cells will fit into the available area – therefore we can just return the collection view’s own size.
When-ever user rotates the device, the size of the collection view changes, therefore we would like to reset the layout.
Prepare is called whenever layout gets invalidated and it is a best place where to pre-calculate cell locations. Then it is possible to return attributes in all of the other methods querying for attributes later on. This gives us the best possible performance.
Items are placed along a circle which is centred in the collection view. As collection view can be under navigation bar, then the frame of the circle needs to take account contentOffset. Moreover, as centre points of items are on the circle, we also need to take account the item size. Calculating positions for items is just a matter of applying simple trigonometry with right-angled triangles.
If we have pre-calculated attributes, then it is straight-forward to return them in the layout attributes methods. When adding or removing items, cells will move to new location with a nice animation by default.
I would like to highlight the fact that content presented here is just a bare minimum for setting up custom collection view layout. UICollectionView is highly configurable.
Setting up collection view
When custom collection view layout is ready, it is time to hook it up to the collection view. Custom collection view layout can be set in storyboard or when initialising collection view or collection view controller.
Implementing a basic collection view controller for just showing one type of cells requires only a little bit of code. Data source methods provide the count of the items and sections and return configured collection view cells.
Adding custom collection view layout requires subclassing UICollectionViewLayout and overriding several methods. The core idea is to provide UICollectionViewAttributes for every cell which UICollectionView will then use for creating and laying out cells.
CustomCollectionViewLayout (GitHub), Xcode 10.1, Swift 4.2