Search code examples
iosobjective-cuicollectionview

Cell spacing in UICollectionView


How do I set cell spacing in a section of UICollectionView? I know there is a property minimumInteritemSpacing I have set it to 5.0 still the spacing is not appearing 5.0. I have implemented the flowout delegate method.

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{

    return 5.0;
}

still I am not getting the desired result. I think its the minimum spacing . Isn't there any way by which I can set the maximum spacing?

simulator sc


Solution

  • I know that the topic is old, but in case anyone still needs correct answer here what you need:

    1. Override standard flow layout.
    2. Add implementation like that:

      - (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
          NSArray *answer = [super layoutAttributesForElementsInRect:rect];
      
          for(int i = 1; i < [answer count]; ++i) {
              UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
              UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];
              NSInteger maximumSpacing = 4;
              NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
      
              if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
                  CGRect frame = currentLayoutAttributes.frame;
                  frame.origin.x = origin + maximumSpacing;
                  currentLayoutAttributes.frame = frame;
              }
          }
          return answer;
      }
      

    where maximumSpacing could be set to any value you prefer. This trick guarantees that the space between cells would be EXACTLY equal to maximumSpacing!!