Adding padding to first and last cell of UICollectionView Adding padding to first and last cell of UICollectionView ios ios

Adding padding to first and last cell of UICollectionView


You can set space at left and right equal to your padding when setting frame of your collection view.

or

You can put condition in cellForItemAtIndexPath that if it is first cell or last cell then manage padding accordingly. that's it.

Or

you can set contentInset property of your collectionView.

for example,

UICollectionView *cv; // your collectionViewcv.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);

Alternatively, you can set the UICollectionView contentInset in storyboard to get it working.


You can achieve that by changing the insets from the Interface Builder. They can be found as Section Insets in the Size Inspector:

Section Insets for Collection View in InterfaceBuilder


Accepted solution works but if you have pagingEnabled the collection view paging gets broken.

For me the solution was to use:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {    return UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)}