Skip to content

5. CollectionView Layouts

Wes Byrne edited this page Jun 8, 2017 · 3 revisions

CBCollectionViewLayout

CollectionView layouts have never been easier. This layout is column based which means you provide the number of columns and cells are placed in the appropriate one. It can be display items all the same size or as a "Pinterest" style layout.

To get started just call var layout = CBCollectionViewLayout(myCollectionView).

If you don't need to change the number of columns dynamically per section you can set layout.columnCount = 2. To change the column count per section or with screen rotations use the delegate method collectionView (collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, numberOfColumnsInSection section: Int) -> Int

You can also set the sectionInsets and minimumColumnSpacing which will affect the width of each column.

With the itemWidth set by the column, you have 3 options to set the height of each item. They are used in the order here. So if aspectRatioForItemAtIndexPath is implemented it is used, otherwise, it checks the next one.

1. aspectRatioForItemAtIndexPath (delegate)
2. heightForItemAtIndexPath (delegate)
3. layout.defaultItemHeight

The delegate method aspectRatioForItemAtIndexPath scales the size of the cell to maintain that ratio while fitting within the caclulated column width.

CBSliderCollectionViewLayout

This CollectionViewLayout provide a simple way to make a horizontal sliding view. All you have to do is say how many cells, and return the cells as normal. Each cell is sized to match the collectionView and scrolling moves horizontal. You can optionally turn on autoScroll to automaticall move through each cell with a given delay.

Note: If autoscroll is used, you must provide the current index to account for manual interaction with the collectionView. If the user scrolls the CV, the layout needs to know where they scrolled to. One place you can do this is shown below.

func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        (collectionView.collectionViewLayout as! CBSliderCollectionViewLayout).currentIndex = indexPath.row
    }
Clone this wiki locally