iOS UICollectionView 的装饰视图

项目需求中需要在 CollectionView的每个section 添加一个背景图片,之前一直没有留意过、一个同事说DecorationView好像可以,试了试果然不错。


iOS UICollectionView 的装饰视图_第1张图片
31730b07-be23-4139-b1ca-c819ad5915be.png

具体做法:
自定义collectionview的layout,创建一个 view继承UICollectionReusableView,在layout中注册。

添加ReusableView

@interface ZYProfileCollectionReusableView()
@property(nonatomic, strong) UIImageView *imageView;
@end
@implementation ZYProfileCollectionReusableView

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = self.bounds;
        _imageView.image = [UIImage imageNamed:@"background_750x220.jpg"];;
        [self addSubview:_imageView];
        
      // 由于在collection View 中没有找到可以获取到该视图的接口,所以暂时用通知来动态改变背景图片
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBgImage:) name:ZY_ACCOUNT_AD_IMAGEREFRESH object:nil];

    }
    
    return self;
}

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    [super applyLayoutAttributes:layoutAttributes];
    _imageView.frame = self.bounds;
}

- (void)changeBgImage:(NSNotification *)noti {

    NSString *imageUrlString = noti.object;

    if (imageUrlString.length==0) {
        return;
    }
    [_imageView zy_setImageFromURLString:imageUrlString placeholderImage:[UIImage imageNamed:@"background_750x220.jpg"]];
}
@end

自定义Layout 继承UICollectionViewFlowLayout 并注册DecorationView

@implementation ZYProfileCollectionViewFlowLayout

NSString * const decorationViewID = @"decorationView";

- (void)prepareLayout {
    [super prepareLayout];
    [self registerClass:[ZYProfileCollectionReusableView class] forDecorationViewOfKind:decorationViewID];//注册装饰视图
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath top:(CGFloat)top {// 实现该方法
    
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:elementKind withIndexPath:indexPath];
    
    attrs.frame = CGRectMake(0, top, [UIScreen mainScreen].bounds.size.width, 100);
    attrs.zIndex = -1;

    
    return attrs;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *superAttrs = [super layoutAttributesForElementsInRect:rect];
    NSMutableArray *attrs = [NSMutableArray arrayWithArray:superAttrs];

    for (UICollectionViewLayoutAttributes *attr in superAttrs) {
        if (attr.indexPath.section==0) {//在第0个section中添加背景图片
            [attrs addObject:[self layoutAttributesForDecorationViewOfKind:decorationViewID atIndexPath:attr.indexPath top:attr.frame.origin.y]];
            break;// 避免多次添加
        }
    }
    return attrs;
}
@end

以上基本完成了,但是发现在CollectionView中并看不到该图片,解决方法,把CollectionViewCell背影颜色设置为clearColor

你可能感兴趣的:(iOS UICollectionView 的装饰视图)