image.png
在UICollectionView展示數(shù)據(jù)時(shí)浮驳,我們希望將cell之間的行間距和列間距為0步藕,在API中我們查到如下屬性:
flowLayout.minimumLineSpacing = 0;
flowLayout.minimumInteritemSpacing = 0;
以上屬性是設(shè)置最小行間距和最小列間距的学搜,設(shè)置之后界面cell中的間距并不是如我們所預(yù)期的一樣焰檩,還是有一部分很小的間距,即使我們?cè)诖碇性O(shè)置依然無(wú)效骏融。
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 0;
}
image.png
自定義類繼承UICollectionViewFlowLayout后在 - (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect; 方法中打印cell的frame:
image.png
可以看到第二個(gè)cell的x比預(yù)想的值要多了0.25链嘀,第三個(gè)cell的x坐標(biāo)正常,第四個(gè)x坐標(biāo)異常档玻,至此找到了問題所在怀泊。我們?cè)O(shè)置了cell行(列)間距的最小值,但是實(shí)際上這還不夠误趴,還需要加一個(gè)最大值進(jìn)行約束包个。,在這個(gè)方法中添加如下代碼:
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
for(int i = 1; i < [attributes count]; ++i) {
UICollectionViewLayoutAttributes *attr = attributes[i];
//NSLog(@" cell frame = %@",NSStringFromCGRect([attr frame]));
//當(dāng)前attributes
UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
//上一個(gè)attributes
UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
//最大列間距冤留,可根據(jù)需要改
NSInteger maximumSpacing = 0;
//前一個(gè)cell的最右邊
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
//如果當(dāng)前一個(gè)cell的最右邊加上我們想要的間距加上當(dāng)前cell的寬度依然在contentSize中碧囊,我們改變當(dāng)前cell的x坐標(biāo)
//如果不加該判斷,UICollectionView只顯示一行纤怒,因?yàn)橄旅嫠衏ell的x值都被加到第一行最后一個(gè)元素的后面了
if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
//前一個(gè)cell的y
NSInteger originy = prevLayoutAttributes.frame.origin.y;
NSInteger maxYSpacing = 0;//最大的行間距
NSInteger currentY = currentLayoutAttributes.frame.origin.y;
if (currentY - originy < 2) {
//同一行的cell糯而,設(shè)置y和前一個(gè)cell的y值一致
CGRect frame = currentLayoutAttributes.frame;
frame.origin.y = prevLayoutAttributes.frame.origin.y + maxYSpacing;
currentLayoutAttributes.frame = frame;
} else {
//下一行的cell,設(shè)置y = 前一cell的y的最大值 + 最大的行間距
CGRect frame = currentLayoutAttributes.frame;
frame.origin.y = CGRectGetMaxY(prevLayoutAttributes.frame) + maxYSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attributes;
}
然后再運(yùn)行泊窘,會(huì)看到之前莫名出現(xiàn)的線已經(jīng)消失了:
image.png