您的当前位置:首页正文

UICollectionView 自定义 Cell - iOS

来源:要发发知识网

使用系统 UICollectionViewCell 的时候遇到渲染 Cell 重叠的现象,因此通过实现自定义 UICollectionViewCell 的方式解决 Cell 图文重叠的问题;
大体流程类似于 TableView 的自定义 cell 方式,感觉比 TableView 还要简单一些;
具体实现方式直接参考如下 code 吧,一些简单的实现没什么花哨,有疑惑的地方可下方留言解答。

首先,创建继承与 UICollectionViewCell 的子类并根据实际需求声明对应的控件属性;

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@class YHFileShelfModel;
@interface FileShelfCell : UICollectionViewCell

@property (nonatomic, strong) YHFileShelfModel *model;

/// 封面
@property (nonatomic, strong) UIImageView *imgViewCover;

/// 下载状态
@property (nonatomic, strong) UILabel *labDownloadState;

/// 名称
@property (nonatomic, strong) UILabel *labName;

@end

NS_ASSUME_NONNULL_END

其次,实现自定义 Cell 相关实例方法和实现自定义 Cell 的样式并为对应的控件进行赋值操作;
注:此处控件赋值方式是通过泛型 model 来实现的

#import "FileShelfCell.h"
#import "YHFileShelfModel.h"
#import "ReadFileManager.h"
#import "UIImageView+AFNetworking.h"
#import "UIImage+FYH.h"

#define IdentifierFileShelf     @"FileShelfList"

@implementation FileShelfCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createFileShelfList];
        [self settingFrameWithFileShelf];
    }
    return self;
}



#pragma mark - ****************************** UI
- (void)createFileShelfList {
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.backgroundColor = [UIColor lightGrayColor];
    [self.contentView addSubview:imgView];
    self.imgViewCover = imgView;
    
    UILabel *labState = [[UILabel alloc] init];
    labState.backgroundColor = [UIColor redColor];
    labState.textColor = [UIColor whiteColor];
    labState.font = [UIFont systemFontOfSize:12.f];
    labState.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:labState];
    self.labDownloadState = labState;
    
    UILabel *labTit = [[UILabel alloc] init];
    labTit.backgroundColor = [UIColor whiteColor];
    labTit.textColor = [UIColor blackColor];
    labTit.font = [UIFont systemFontOfSize:14.f];
    labTit.textAlignment = NSTextAlignmentLeft;
    [self.contentView addSubview:labTit];
    self.labName = labTit;
}



#pragma mark - ****************************** Frame
- (void)settingFrameWithFileShelf {
    [self.imgViewCover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(0);
        make.left.equalTo(self.contentView).offset(0);
        make.right.equalTo(self.contentView).offset(0);
        make.bottom.equalTo(self.contentView).offset(-20);
    }];
    
    [self.labDownloadState mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imgViewCover.mas_bottom).offset(0);
        make.left.equalTo(self.contentView).offset(0);
        make.bottom.equalTo(self.contentView).offset(0);
        make.width.equalTo(self.contentView.mas_width).multipliedBy(0.3);
    }];
    
    [self.labName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imgViewCover.mas_bottom).offset(0);
        make.left.equalTo(self.labDownloadState.mas_right).offset(0);
        make.right.equalTo(self.contentView).offset(0);
        make.bottom.equalTo(self.contentView).offset(0);
    }];
}



#pragma mark - ****************************** Set model
- (void)setModel:(YHFileShelfModel *)model {
    _model = model;
    
    NSString *imgLocalPath = [kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", LocalFile_FilePath_FilesCover, model.cover.lastPathComponent]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:imgLocalPath]) {
        [_imgViewCover setImage:[UIImage imageWithContentsOfFile:imgLocalPath]];
    } else {
        NSString *imgPath = [NSString  model.cover.lastPathComponent];
        NSLog(@"******** 文件图片(线上):%@", imgPath.lastPathComponent);
        [_imgViewCover setImageWithURL:[NSURL URLWithString:imgPath]
                      placeholderImage:[UIImage imageWithColor:[UIColor lightGrayColor]]];
    }
    _labDownloadState.text = [ReadFileManager getFileDownloadState:model.downloadState];
    _labName.text = model.name;
}

@end

最后,在 UICollectionView 初始化和代理方法中引用自定义的 Cell 并与数据源相互关联即可,记得先引用自定义 Cell 和泛型 model 的 import 头文件
注:实例化控件和控件代理方法中记得将系统的 Cell 均替换为自定义 Cell 否则会导致 crash 抛出如下异常信息提示,切勿大意!

unrecognized selector sent to instance 0x7f7f66728d30
- (UICollectionView *)fileShelfView {
    if (!_fileShelfView) {
        NSInteger topHeight = STATUS_BAR_HEIGHT + CGRectGetHeight(_navView.frame);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical; // 水平布局
        layout.itemSize = CGSizeMake((SCREEN_WIDTH - 40) / 3, (CONTENT_HEIGHT + 64) / 4); // 每个 item 尺寸
//        layout.minimumLineSpacing = 10; // 行间距
//        layout.minimumInteritemSpacing = 10; // 列k间距
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); // 分区偏移量
        UICollectionView *collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, topHeight, SCREEN_WIDTH, CONTENT_HEIGHT)
                                                       collectionViewLayout:layout];
        collect.backgroundColor = [UIColor colorWithRed:0.95f green:0.95f blue:0.95f alpha:1.00f];
        collect.delegate = self;
        collect.dataSource = self;
        [collect registerClass:[FileShelfCell class] forCellWithReuseIdentifier:IdentifierFileShelfCell];
        _fileShelfView = collect;
    }
    return _fileShelfView;
}



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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _fileShelfData.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FileShelfCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:IdentifierFileShelfCell forIndexPath:indexPath];
    cell.model = _fileShelfData[indexPath.row];
    return cell;
}

以上便是此次分享的全部内容,希望能对大家有所帮助!