Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView container padding

I am trying to add padding to the container of a UICollectionView. I would like it to appear as such that there is a 10pt padding all around. So in the example screen, there is a 10pt padding on the bottom from:

layout.minimumInteritemSpacing = layout.minimumLineSpacing = 10;

I am using a UICollectionViewFlowLayout to layout the cells. I have also tried a "trick" where I add a 10pt view on top, but the content doesn't appear to scroll through the view since they are separate.enter image description here

like image 959
nmock Avatar asked Nov 07 '13 18:11

nmock


3 Answers

Please try to put following code inside viewDidLoad():

collectionView!.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) 

This will add padding to every side of the collectionView.


PS: I know the question is here for a while but it might help somebody ;)

like image 114
exmaxx Avatar answered Nov 06 '22 18:11

exmaxx


It seems like the sectionInset property of your UICollectionViewFlowLayout is what you need to modify.

You can use a UIEdgeInsetsMake to create a UIEdgeInsets with margins for top, left, right, and bottom, and set this to the sectionInset property.

Here's the documentation for UICollectionViewFlowLayout: https://developer.apple.com/library/ios/documentation/uikit/reference/UICollectionViewFlowLayout_class/Reference/Reference.html

like image 24
Marcel Puyat Avatar answered Nov 06 '22 18:11

Marcel Puyat


I used a couple of methods from the UICollectionViewDelegateFlowLayout delegate to accomplish what I was looking for. I was attempting to add 'padding' to cells that had a shadow. This was to ensure they had the effect of 'floating,' and were not touching the edges of the UICollectionView.

First, call the sizeForItemAt indexPath method and give the cells a size:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.width * 0.80, height: collectionView.bounds.height * 0.98)
}

Then, call the insetForSectionAt section method, and set the insets for the cells:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 20, left: 25, bottom: 20, right: 25)
}
like image 30
andrewlundy Avatar answered Nov 06 '22 17:11

andrewlundy