1. 程式人生 > >解決UICollectionView間隔設定為0時仍有空隙的問題

解決UICollectionView間隔設定為0時仍有空隙的問題

@interface WHUICollectionViewFlowLayout : UICollectionViewFlowLayout

@end

@implementation LZUICollectionViewFlowLayout

#pragma mark - cell的左右間距

- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {

NSMutableArray * answer = [[superlayoutAttributesForElementsInRect:rect] mutableCopy];

/*

處理左右間距 */

for(int i = 1; i < [answer count]; ++i) {

UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];

UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];

NSInteger maximumSpacing = 0;

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;

}

@end

重寫layoutAttributesForElementsInRect方法即可