Search code examples
iosuicollectionviewuicollectionviewlayout

Placing a margin around each edge of the UICollectionView


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?


Solution

  • In

    (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    }
    

    you can give your cells some margin on the left side.

    Or you can create custom cells, which have a margin.

    or you can set the property .sectionInset of your CollectionviewFlowLayout, which should be the easiest way (if you use FlowLayout)