There are a few aspects to handling spacing and size of UICollectionViews and their cells.
Lets start with the spacing around the actual uicollectionview. To do this we effectively add padding or edge insets. You can add edges to all sides of the collection view.
1 |
myCollectionView.contentInset = UIEdgeInsets(top: 7.0, left: 1.0, bottom: 144.0, right: 1.0) |
Now what about the cells within the UICollectionView. We can set the size of these cells, and the spacing that appears between each cell.
These methods are part of the UICollectionViewDelegateFlowLayout which should be added as a protocol. This will create a grid effect by default which can then be amended using the methods below.
To set the cell size, we return the desired width and height of the cell as a CGSize object in the method collectionView:layout:sizeForItemAtIndexPath:.
1 2 3 |
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.size.width / 2.0, height: 151.0) } |
To set the minimum space horizontally between each cell, we return a float value from the method collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
1 2 3 |
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 3.0 } |
To set the minumum spacing vertically between the cells, or line height. We return a float value from the method collectionView:layout:minimumLineSpacingForSectionAtIndex:
1 2 3 |
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 5.0 } |
A sample of the code can be found in a Playground file on GitHub