美文网首页iOS视图
UICollectionView的Section背景颜色

UICollectionView的Section背景颜色

作者: 心猿意码_ | 来源:发表于2022-03-31 09:27 被阅读0次
  • 先看效果


    WechatIMG27.jpeg
  • 直接上代码

封装(XLCollectionReusableView)

//
//  XLCollectionReusableView.h
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface XLCollectionReusableView : UICollectionReusableView

@end

NS_ASSUME_NONNULL_END


//
//  XLCollectionViewFlowLayout.h
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol JHCollectionViewDelegateFlowLayout <UICollectionViewDelegateFlowLayout>

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section;

@end

@interface XLCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *decorationViewAttrs;

@end

NS_ASSUME_NONNULL_END

封装(XLCollectionViewLayoutAttributes)

//
//  XLCollectionViewLayoutAttributes.h
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface XLCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes
@property (nonatomic, strong) UIColor *backGroundColor;
@end

NS_ASSUME_NONNULL_END
//
//  XLCollectionReusableView.m
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import "XLCollectionReusableView.h"
#import "XLCollectionViewLayoutAttributes.h"

@implementation XLCollectionReusableView
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    [super applyLayoutAttributes:layoutAttributes];
    if ([layoutAttributes isKindOfClass:[XLCollectionViewLayoutAttributes class]]) {
        XLCollectionViewLayoutAttributes *attr = (XLCollectionViewLayoutAttributes *)layoutAttributes;
        self.backgroundColor = attr.backGroundColor;
    }
}
@end

封装(XLCollectionViewLayoutAttributes)

//
//  XLCollectionViewLayoutAttributes.m
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import "XLCollectionViewLayoutAttributes.h"

@implementation XLCollectionViewLayoutAttributes

@end

//
//  XLCollectionViewFlowLayout.m
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import "XLCollectionViewFlowLayout.h"
#import "XLCollectionReusableView.h"
#import "XLCollectionViewLayoutAttributes.h"

NSString *const XLCollectionViewSectionBackground = @"XLCollectionViewSectionBackground";

@implementation XLCollectionViewFlowLayout
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.decorationViewAttrs = [NSMutableArray array];
        [self setup];
    }
    return self;
}

- (void)setup
{
    [self registerClass:[XLCollectionReusableView class] forDecorationViewOfKind:XLCollectionViewSectionBackground];
}

- (void)prepareLayout
{
    [super prepareLayout];
    [self.decorationViewAttrs removeAllObjects];

    NSInteger numberOfSections = [self.collectionView numberOfSections];
    id delegate = self.collectionView.delegate;
    if (!numberOfSections || ![delegate conformsToProtocol:@protocol(JHCollectionViewDelegateFlowLayout)]) {
        return;
    }
    
    for (NSInteger section = 0; section < numberOfSections; section++) {
        NSInteger numberOfItems = [self.collectionView numberOfItemsInSection:section];
        if (numberOfItems <= 0) {
            continue;
        }
        UICollectionViewLayoutAttributes *firstItem = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
        UICollectionViewLayoutAttributes *lastItem = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:numberOfItems - 1 inSection:section]];
        if (!firstItem || !lastItem) {
            continue;
        }
        
        UIEdgeInsets sectionInset = [self sectionInset];

        if ([delegate respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
            UIEdgeInsets inset = [delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:section];
            sectionInset = inset;
        }

        
        CGRect sectionFrame = CGRectUnion(firstItem.frame, lastItem.frame);
        sectionFrame.origin.x -= sectionInset.left;
        sectionFrame.origin.y -= sectionInset.top;
        
        if (self.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
            sectionFrame.size.width += sectionInset.left + sectionInset.right;
            sectionFrame.size.height = self.collectionView.frame.size.height;
        } else {
            sectionFrame.size.width = self.collectionView.frame.size.width;
            sectionFrame.size.height += sectionInset.top + sectionInset.bottom;
        }
        
        // 2、定义
        XLCollectionViewLayoutAttributes *attr = [XLCollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:XLCollectionViewSectionBackground withIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
        attr.frame = sectionFrame;
        attr.zIndex = -1;
        
        attr.backGroundColor = [delegate collectionView:self.collectionView layout:self backgroundColorForSection:section];
        [self.decorationViewAttrs addObject:attr];
    }

}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
     NSMutableArray *attrs = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    for (UICollectionViewLayoutAttributes *attr in self.decorationViewAttrs) {
        
        if (CGRectIntersectsRect(rect, attr.frame)) {
            [attrs addObject:attr];
        }
    }
    return attrs;
}

- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    if ([elementKind isEqualToString:XLCollectionViewSectionBackground]) {
        return [self.decorationViewAttrs objectAtIndex:indexPath.section];
    }
    return [super layoutAttributesForDecorationViewOfKind:elementKind atIndexPath:indexPath];
}
@end

使用方式

//
//  ViewController.h
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

//
//  ViewController.m
//  UICollectionViewSctionColor
//
//  Created by yxl on 2022/3/28.
//

#import "ViewController.h"
#import "XLCollectionViewFlowLayout.h"

@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, JHCollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    XLCollectionViewFlowLayout *xlFlowLayout = [[XLCollectionViewFlowLayout alloc] init];
    xlFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    xlFlowLayout.itemSize = CGSizeMake(50, 50);
    xlFlowLayout.minimumInteritemSpacing = 30;
    xlFlowLayout.minimumLineSpacing = 30;
    xlFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:xlFlowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 13;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    return cell;
}

#pragma mark - JHCollectionViewDelegateFlowLayout
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section
{
    return [@[
              [UIColor redColor],
              [UIColor greenColor],
              [UIColor yellowColor]
              ] objectAtIndex:section];
}


@end

求赞!!!

Demo

相关文章

网友评论

    本文标题:UICollectionView的Section背景颜色

    本文链接:https://www.haomeiwen.com/subject/gklwjrtx.html