UICollectionView 修改組背景顏色
.h
HTCollectionViewLayout : UICollectionViewFlowLayout
HTCollectionViewLayoutAttributes:UICollectionViewLayoutAttributes
HTCollectionReusableView :UICollectionReusableView
@protocol HTCollectionViewLayoutDelegate <UICollectionViewDelegateFlowLayout>
// Section 背景顏色
@optional
-(UIColor *)collectionview:(UICollectionView
@end
.m
- (void)prepareLayout{
[superprepareLayout];
[selfregisterClass:[HTCollectionReusableViewclass] forDecorationViewOfKind:@"HTCollectionReusableView"];
// 獲取組數
NSInteger sections = [self.collectionViewnumberOfSections];
// 獲取代理物件
__strongid<HTCollectionViewLayoutDelegate> delegate = self.collectionView.delegate;
// 是否實現代理方法
if ([delegate respondsToSelector:@selector(collectionview:colorForSection:)]) {
[self.decorationViewAttrsremoveAllObjects];
// 遍歷組
for(NSInteger section = 0;section<sections;section ++){
// 獲取Item數
NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:section];
if(numberOfItems >0){
// 獲取第一個item Attributes
UICollectionViewLayoutAttributes *fristAttributes = [selflayoutAttributesForItemAtIndexPath:[NSIndexPathindexPathForRow:0inSection:section]];
UICollectionViewLayoutAttributes *lastAttrbutes = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:(numberOfItems - 1) inSection:section]];
// 獲取最小包含frame
CGRect sectionFrame = CGRectUnion(fristAttributes.frame, lastAttrbutes.frame);
if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
sectionFrame.size.height = self.collectionView.frame.size.height;
}else{
sectionFrame.size.width = self.collectionView.frame.size.width;
}
HTCollectionViewLayoutAttributes *attr = [HTCollectionViewLayoutAttributeslayoutAttributesForDecorationViewOfKind:@"HTCollectionReusableView"withIndexPath:[NSIndexPathindexPathForItem:0inSection:section]];
attr.frame = sectionFrame;
attr.zIndex = -1;
attr.backgroudColor = [delegate collectionview:self.collectionView colorForSection:section];
[self.decorationViewAttrs addObject:attr];
}
}
}else{
return ;
}
}
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
NSMutableArray *attrs = [NSMutableArrayarray];
[attrs addObjectsFromArray:[[superlayoutAttributesForElementsInRect:rect] mutableCopy]];
for(UICollectionViewLayoutAttributes *attr inself.decorationViewAttrs){
if(CGRectIntersectsRect(rect, attr.frame)){
[attrs addObject:attr];
}
}
return attrs;
}
@implementation HTCollectionReusableView
-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{
[super applyLayoutAttributes:layoutAttributes];
HTCollectionViewLayoutAttributes *attr = (HTCollectionViewLayoutAttributes *)layoutAttributes;
self.backgroundColor = attr.backgroudColor;
}