Ios development -- fixed the inconsistency between cell spacing and settings of UICollectionView
When we use UICollectionView to display data, we sometimes want to adjust the cell spacing to a value we want, and then check the API to see that there is such an attribute:
- (CGFloat)minimumInteritemSpacing { return 0;}
However, in many cases, we will find that such writing cannot meet our requirements, and there is still a gap between cells that does not know how to generate.
We know that the cell spacing is determined by the cell size itemSize and the section indent sectionInset. Through the two data, UICollectionView dynamically places the cell in the corresponding position, however, it is useless even if we call the inset method.
- (UIEdgeInsets)sectionInset{ return UIEdgeInsetsMake(0, 0, 0, 0);}
<注:我想实现的是0间距,其他情况类似>
As you can see, After inheriting UICollectionViewFlowLayout, print the frame results of these cells in the-layoutAttributesForElementsInRect: method.
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{ NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; for (UICollectionViewLayoutAttributes *attr in attributes) { NSLog(@"%@", NSStringFromCGRect([attr frame])); }}
From the above two rows, we can see that my height is 42.8, but the x distance between the two cells is 46, that is, there is a spacing of about 3px.
In fact, just like the name of minimumInteritemSpacing, this attribute sets the minimum spacing, so what we actually need is a "maximumInteritemSpacing", that is, the maximum spacing. To solve this problem, you need to make some calculations by yourself.
Still inherit UICollectionViewFlowLayout, and then add the following code in-layoutAttributesForElementsInRect: method:
// From the second loop to the last for (int I = 1; I <[attributes count]; ++ I) {// current attributes UICollectionViewLayoutAttributes * currentLayoutAttributes = attributes [I]; // The Last attributes * prevlayoutattriattributes = attributes [I-1]; // The maximum interval we want to set, modify NSInteger maximumSpacing = 0 as needed; // NSInteger origin = CGRectGetMaxX (prevLayoutAttributes. frame); // If the rightmost side of the current cell is added with the spacing we want and the width of the current cell is still in contentSize, the result of changing the origin location of the current cell without this judgment is that UICollectionView only displays one row, the reason is that the x values of all cells below are added to the end of the last element of the first line if (origin + maximumSpacing + currentLayoutAttributes. frame. size. width <self. collectionViewContentSize. width) {CGRect frame = currentLayoutAttributes. frame; frame. origin. x = origin + maximumSpacing; currentLayoutAttributes. frame = frame ;}}
The reason comment has been explained in detail. In this way, the cell spacing problem can be solved. Run the command again. The result is very good: