今天做項(xiàng)目的時(shí)候做那個(gè)標(biāo)簽 用collectionview 設(shè)置了間距, 發(fā)現(xiàn)間距不相等 我第一時(shí)間想到可能是設(shè)置sectionInset或者itemsize的問(wèn)題,但是我去修改怎么去設(shè)置都沒(méi)效果
就像這樣:
Snip20161223_2.png
Snip20161223_3.png
item之間的間隙不相等, 我當(dāng)時(shí)有點(diǎn)納悶了 不知道什么原因
后來(lái)看見(jiàn)這篇文章http://blog.csdn.net/u013604612/article/details/41450167解決了
解決辦法:
寫個(gè)類繼承UICollectionViewFlowLayout,在重寫的類里面重寫
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSMutableArray* attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
for (UICollectionViewLayoutAttributes *attr in attributes) {
NSLog(@"%@", NSStringFromCGRect([attr frame]));
}
//從第二個(gè)循環(huán)到最后一個(gè)
for(int i = 1; i < [attributes count]; ++i) {
//當(dāng)前attributes
UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
//上一個(gè)attributes
UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
//我們想設(shè)置的最大間距夷磕,可根據(jù)需要改
NSInteger maximumSpacing = 5.0;
//前一個(gè)cell的最右邊
NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
//如果當(dāng)前一個(gè)cell的最右邊加上我們想要的間距加上當(dāng)前cell的寬度依然在contentSize中肝陪,我們改變當(dāng)前cell的原點(diǎn)位置
//不加這個(gè)判斷的后果是姐直,UICollectionView只顯示一行俭驮,原因是下面所有cell的x值都被加到第一行最后一個(gè)元素的后面了
if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = currentLayoutAttributes.frame;
frame.origin.x = origin + maximumSpacing;
currentLayoutAttributes.frame = frame;
}
}
return attributes;
}