Adding padding to first and last cell of UICollectionView

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


For Swift 5:

In your viewDidLoad, set contentInset property of the collectionView like so:

self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);

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 collectionView

cv.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);

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


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)
}