Cell spacing in UICollectionView

后端 未结 26 3737
旧巷少年郎
旧巷少年郎 2020-11-22 15:53

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 spaci

26条回答
  •  盖世英雄少女心
    2020-11-22 16:35

    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!!

提交回复
热议问题