場景描述: 在UICollectionViewFlowLayout的子類里重寫layoutAttributesForElementsInRect方法, 為了實(shí)現(xiàn)不同的cell效果, 可以修改某組或某個(gè)Item的UICollectionViewLayoutAttributes.
效果圖如下:
現(xiàn)在要修改第一組(中間組只有一個(gè)item)的item的size, 寬為屏幕的寬度, 高度為原來item高度的2倍
在prepareLayout方法里設(shè)置好item的布局, 然后在layoutAttributesForElementsInRect方法里修改第1組Item的UICollectionViewLayoutAttributes屬性
代碼如下:
//此方法會(huì)計(jì)算并返回每個(gè)item的位置和大小胀葱,換句話說就是collectionView里面的布局是怎樣布局的就根這個(gè)方法的返回值有關(guān)
//此方法會(huì)先計(jì)算一定數(shù)量的數(shù)據(jù)坠陈,當(dāng)你繼續(xù)滾動(dòng)需要一些新數(shù)據(jù)時(shí)會(huì)再次來計(jì)算新的數(shù)據(jù)
//只要在這里有過返回的數(shù)據(jù)都會(huì)緩存起來苏研,下次再滾回來不會(huì)再幫你計(jì)算新數(shù)據(jù)
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//獲取原本的布局?jǐn)?shù)據(jù)
NSArray *arr = [super layoutAttributesForElementsInRect:rect];
// NSLog(@"ZFBFunctionListFlowLayout + layoutAttributesForElementsInRect");
//循環(huán)遍歷所有布局?jǐn)?shù)據(jù)
for (UICollectionViewLayoutAttributes *attr in arr) {
if(attr.indexPath.section == 1){
//如果是第1組,就把它的寬度放大
CGRect frame = attr.frame;
frame.size.width = self.collectionView.bounds.size.width;
frame.size.height = frame.size.height * 2;
attr.frame = frame;
// break;//因?yàn)橹恍枰倪@一個(gè)来庭,后面都不需要改,所以break結(jié)束這個(gè)循環(huán)
}
if (attr.indexPath.section == 2) {
CGRect frame = attr.frame;
frame.origin.y += frame.size.height;
attr.frame = frame;
}
}
return arr;
}
出現(xiàn)Warning:
Logging only once for UICollectionViewFlowLayout cache mismatched frame
This is likely occurring because the flow layout subclass ZFBFunctionListFlowLayout is modifying attributes returned by UICollectionViewFlowLayout without copying them
大概意思是說我們自定義的布局對(duì)象正在修改由UICollectionViewFlowLayout返回的UICollectionViewLayoutAttributes屬性, 而這個(gè)屬性沒有經(jīng)過copy處理.
解決方法:
把原來的
NSArray *arr = [super layoutAttributesForElementsInRect:rect];
替換成
NSArray *arr = [[NSArray alloc]initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];
這樣就解決了:)