Placing a margin around each edge of the UICollectionView

Adam picture Adam · Jun 5, 2013 · Viewed 32.1k times · Source

When the UICollectionView is populated with items they always go right to the edges of the UICollectionView like so:

---------------
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
|X X X X X X X|
---------------

I would like to place a margin around each edge like so:

---------------
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
| X X X X X X |
---------------

I tried to achieve this by placing the UICollectionView inside its hosting UIView by setting its Frame to simulate a border but it scrolls within the Frame so gets cut off at the top and bottom and the scroller also appears in the bounds of the frame.

I have looked at the API but I cannot see anything obvious to achieve this. Any ideas?

Answer

Tyler Cloutier picture Tyler Cloutier · Apr 2, 2014

I know this is an old question, but don't forget that UICollectionView inherits from UIScrollView.

UICollectionView *collectionView = [[UICollectionView alloc] init];
collectionView.contentInset = UIEdgeInsetsMake(x.x, x.x, x.x, x.x);
// Swift 3 for good measure
let collectionView = UICollectionView()
collectionView.contentInset = UIEdgeInsets(top: x.x, left: x.x, bottom: x.x, right: x.x)

Be aware that both contentInset and sectionInset may change the spacing of cells in your view. For more information on that, see this post.