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.
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 ;)
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With