解决UICollectionView的cell间距与设置不符问题

2016-08-19  本文已影响291人  qing_shan

解决UICollectionView的cell间距与设置不符问题

在用UICollectionView展示数据时,有时我们希望将cell的间距调成一个我们想要的值,然后查API可以看到有这么一个属性:

list text here

(CGFloat)minimumInteritemSpacing { return 0; }

然而很多情况下我们会发现,这样写不能满足我们的要求,cell之间仍然有一个不知道怎么产生的间距。

我们知道cell的间距是由cell的大小itemSize和section的缩进sectionInset共同决定的,通过这两个数据,UICollectionView动态地将cell放在相应的位置,然而即使我们接着调用inset方法也没有用。

(UIEdgeInsets)sectionInset { return UIEdgeInsetsMake(0, 0, 0, 0); }

<注:我想实现的是0间距,其他情况类似>

可以看到,继承UICollectionViewFlowLayout后在- layoutAttributesForElementsInRect:方法中打印一下这些cell的frame的结果

-(NSArray)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArrayattributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

for(UICollectionViewLayoutAttributes *attrinattributes) {NSLog(@"%@", NSStringFromCGRect([attr frame]));}

}

从上面两行就可以看出来,我的高度是42.8,然而两个cell的x值间距却为46,也就是说有大约3px的间距。 其实,正如minimumInteritemSpacing的名字一样,这个属性设置的是间距的最小值,那么,我们实际需要的应该是一个"maximumInteritemSpacing",也就是最大间距。要解决这个问题,需要自己做一些计算。

依旧是继承UICollectionViewFlowLayout,然后在- layoutAttributesForElementsInRect:方法中添加如下代码:

//从第二个循环到最后一个 for(int i = 1; i < [attributes count]; ++i) { //当前attributes UICollectionViewLayoutAttributescurrentLayoutAttributes = attributes[i]; //上一个attributes UICollectionViewLayoutAttributesprevLayoutAttributes = attributes[i - 1]; //我们想设置的最大间距,可根据需要改 NSInteger maximumSpacing = 0; //前一个cell的最右边 NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame); //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置 //不加这个判断的后果是,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; } }

上一篇下一篇

猜你喜欢

热点阅读