UICollectionView spacing margins
You can use the collectionView:layout:insetForSectionAtIndex:
method for your UICollectionView
or set the sectionInset
property of the UICollectionViewFlowLayout
object attached to your UICollectionView
:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{ return UIEdgeInsetsMake(top, left, bottom, right);}
or
UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];[aFlowLayout setSectionInset:UIEdgeInsetsMake(top, left, bottom, right)];
Updated for Swift 5
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 25, left: 15, bottom: 0, right: 5) }
Setting up insets in Interface Builder like shown in the screenshot below
Will result in something like this:
To add spacing on the entire UICollectionView
:
UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout*) collection.collectionViewLayout;flow.sectionInset = UIEdgeInsetsMake(topMargin, left, bottom, right);
To play with the spacing between elements of the same row (column if you're scrolling horizontally), and their sizes:
flow.itemSize = ...;flow.minimumInteritemSpacing = ...;