iOS 开发程序员iOS学习笔记

UICollectionView Cell设置cell的行(列)

2017-10-06  本文已影响178人  apk收集均
image.png

在UICollectionView展示数据时,我们希望将cell之间的行间距和列间距为0,在API中我们查到如下属性:

flowLayout.minimumLineSpacing = 0;
flowLayout.minimumInteritemSpacing = 0;

以上属性是设置最小行间距和最小列间距的,设置之后界面cell中的间距并不是如我们所预期的一样,还是有一部分很小的间距,即使我们在代理中设置依然无效。

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

可以看到第二个cell的x比预想的值要多了0.25,第三个cell的x坐标正常,第四个x坐标异常,至此找到了问题所在。我们设置了cell行(列)间距的最小值,但是实际上这还不够,还需要加一个最大值进行约束。,在这个方法中添加如下代码:

- (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]));
        //当前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一个attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //最大列间距,可根据需要改
        NSInteger maximumSpacing = 0;
        //前一个cell的最右边
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的x坐标
        //如果不加该判断,UICollectionView只显示一行,因为下面所有cell的x值都被加到第一行最后一个元素的后面了
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
        //前一个cell的y
        NSInteger originy = prevLayoutAttributes.frame.origin.y;
        NSInteger maxYSpacing = 0;//最大的行间距
        NSInteger currentY = currentLayoutAttributes.frame.origin.y;
        if (currentY - originy < 2) {
        //同一行的cell,设置y和前一个cell的y值一致
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.y = prevLayoutAttributes.frame.origin.y + maxYSpacing;
            currentLayoutAttributes.frame = frame;
        } else {
        //下一行的cell,设置y = 前一cell的y的最大值 + 最大的行间距
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.y = CGRectGetMaxY(prevLayoutAttributes.frame) + maxYSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    return attributes;
}

然后再运行,会看到之前莫名出现的线已经消失了:

image.png
上一篇 下一篇

猜你喜欢

热点阅读