17

How to adjust the spacing between sections of collection view.

enter image description here

Bhanu Birani
  • 1,286
  • 1
  • 13
  • 22

5 Answers5

18

You can use the method to implement this:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{
    //{top, left, bottom, right}

    if ([[sectionHeaderStatusArray objectAtIndex:section] boolValue]) {
        return UIEdgeInsetsMake(23, 19, 46, 14);
    }

      return UIEdgeInsetsZero;
}
Tyson Vignesh
  • 315
  • 2
  • 14
Mayank Birani
  • 181
  • 1
  • 4
12

Here's the Swift 4.2 version.

This lets you set various inset configurations for different sections.

/// Formats the insets for the various headers and sections.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    if section == 0 {
        // No insets for header in section 0
        return UIEdgeInsets.zero
    } else {
        // Normal insets for collection
        return UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
    }
}
Jason Machacek
  • 994
  • 1
  • 8
  • 18
10

Header height can be adjusted by adjusting the params of the collection view layout. Following is the code which works perfectly fine.

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{
    if ([[sectionHeaderArray objectAtIndex:section] boolValue]) {
        return UIEdgeInsetsMake(10, 10, 10, 10);
    }
      return UIEdgeInsetsZero;
}
Swan
  • 305
  • 2
  • 6
3

This is a layout issue, thus the answer will be in whatever layout you're using for the collection view. If you're using UICollectionViewFlowLayout then you'll want to set the sectionInset. e.g.

self.collectionView.collectionViewLayout.sectionInset = UIEdgeInsetsZero;
Graham Perks
  • 23,007
  • 8
  • 61
  • 83
  • Give more information then. What layout are you using? I think you need to investigate into whatever layout it is. – Graham Perks Feb 08 '15 at 20:57
  • For flow layout you can do this if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.sectionInset = UIEdgeInsets.zero } – Usuf Nov 11 '18 at 07:32
2

Try this:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{
    if ([[sectionHeaderArray objectAtIndex:section] boolValue]) {
        return UIEdgeInsetsMake(top, left, bottom, right);
    }
      return UIEdgeInsetsZero;
}