美文网首页
一种把UITableView,UICollectionView的

一种把UITableView,UICollectionView的

作者: 小立哥 | 来源:发表于2021-07-06 10:42 被阅读0次

    前言

    开发中经常使用UITableView和UICollectionView时,都是放在ViewController中,去实现DataSource和Delegate协议中的各种方法。一方面,需要实现的方法有多个,代码编写效率较低,二一方面会让ViewController的代码行数暴增,后期维护会非常吃力。现在把DataSource和Delegate,分离到一个单独文件中实现,ViewController只需要一行代码来实现DataSource和Delegate的配置。

    实现思路

    单独创建DataSource和Delegate文件,把UITableView和UICollectionView的dataSource和delegate指向这个两个类初始化的对象,达到在独立的文件中实现DataSource和delegate协议。

    配置DataSource文件

    截屏2021-07-07 上午10.00.20.png

    在.h文件中,定义dataArray数组作为数据源数组,定义numberOfSection作为标记group的数量。

    //数据源数组
    @property (nonatomic,strong) NSArray *dataArray;
    //section的数量
    @property (nonatomic,assign) NSInteger numberOfSection;
    

    CellIDConfigureBlock来返回cell的identifier,用来实现cell的重用机制。

    typedef NSString *(^CellIDConfigureBlock)(NSIndexPath *indexPath,id model);
    

    CellConfigureBlock和ConfigureCellDelegate来实现配置cell的显示。

    //cell个性化配置的block
    typedef void(^CellConfigureBlock)(NSIndexPath *indexPath,id model,id cell);
    
    @protocol ConfigureCellDelegate
    - (void)configureCellWithModel:(id)model;
    @end
    

    ReusableViewIDConfigureBlock和ReusableViewConfigureBlock是两个collectionview的header和footer

    //配置collection header和footer的id,返回的字典格式类似于@{UICollectionElementKindSectionHeader:@"header",UICollectionElementKindSectionFooter:@"footer"},key必须为UICollectionElementKindSectionHeader,UICollectionElementKindSectionFooter
    typedef NSDictionary *(^ReusableViewIDConfigureBlock)(NSIndexPath *indexPath);
    //配置collectionview的header和footerview,返回的字典格式类似于@{UICollectionElementKindSectionHeader:[weakself createCollectionHeaderView],UICollectionElementKindSectionFooter:[weakself createCollectionFooterView]},key必须为UICollectionElementKindSectionHeader,UICollectionElementKindSectionFooter
    typedef void (^ReusableViewConfigureBlock)(NSIndexPath *indexPath,UICollectionReusableView *reusableView,NSString *kind);
    

    剩下就是按需求自定义几个初始化DataSource的方法。这个可以根据自身需求灵活的定义需要的参数,以下是我自己使用时定义的几个方法。
    最常用的就是以下这两个。
    第一个就仅有三个参数,dataArray是配置的数据源,cellIDConfigureBlock是cell的identifier,CellConfigureBlock配置cell的显示。

    - (instancetype)initWithDataArray:(NSArray *)dataArray
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock;
    

    第二个就比第一个多一个numberOfSection参数,用于分组的tableview和collectionview

    - (instancetype)initWithDataArray:(NSArray *)dataArray
                      numberOfSection:(NSInteger)numberOfSection
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock;
    

    以下是全部的.h代码

    //
    //  DataSource.h
    //  CustomDataSourceAndDelegate
    //  该类是一个tableview和collectionview都能使用的datasource
    //  只需要初始化该类,然后把该类赋值给tableview或者collectionview,就能实现功能,具体的使用方法可以参考example
    //  如果涉及到该类未实现的datasource的协议中的方法时,可以自己新建一个datasource的类,然后继承该类,在新建的类中实现自己的方法,即可使用
    //  Created by zjl on 2017/8/9.
    //  Copyright © 2017年 zjlzjl. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    @protocol ConfigureCellDelegate
    - (void)configureCellWithModel:(id)model;
    @end
    
    @interface DataSource : NSObject<UITableViewDataSource,UICollectionViewDataSource>
    //数据源数组
    @property (nonatomic,strong) NSArray *dataArray;
    //section的数量
    @property (nonatomic,assign) NSInteger numberOfSection;
    //配置cellIdentifer的block
    typedef NSString *(^CellIDConfigureBlock)(NSIndexPath *indexPath,id model);
    //cell个性化配置的block
    typedef void(^CellConfigureBlock)(NSIndexPath *indexPath,id model,id cell);
    //配置collection header和footer的id,返回的字典格式类似于@{UICollectionElementKindSectionHeader:@"header",UICollectionElementKindSectionFooter:@"footer"},key必须为UICollectionElementKindSectionHeader,UICollectionElementKindSectionFooter
    typedef NSDictionary *(^ReusableViewIDConfigureBlock)(NSIndexPath *indexPath);
    //配置collectionview的header和footerview,返回的字典格式类似于@{UICollectionElementKindSectionHeader:[weakself createCollectionHeaderView],UICollectionElementKindSectionFooter:[weakself createCollectionFooterView]},key必须为UICollectionElementKindSectionHeader,UICollectionElementKindSectionFooter
    typedef void (^ReusableViewConfigureBlock)(NSIndexPath *indexPath,UICollectionReusableView *reusableView,NSString *kind);
    
    - (instancetype)initWithDataArray:(NSArray *)dataArray
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock;
    
    - (instancetype)initWithDataArray:(NSArray *)dataArray
                      numberOfSection:(NSInteger)numberOfSection
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock;
    
    //datasource的初始化方法
    - (instancetype)initWithDataArray:(NSArray *)dataArray//datasource的数据源数组
                      numberOfSection:(NSInteger)numberOfSection//section数量
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock//cell重用的identifer
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock//配置cell样式的block
         ReusableViewIDConfigureBlock:(ReusableViewIDConfigureBlock)reusableViewIDConfigureBlock//collectionviewsectionview的identifier,这个地方需要配置一个字典来返回
           ReusableViewConfigureBlock:(ReusableViewConfigureBlock)reusableViewConfigureBlock;//配置collectionviewsectionview的block
    @end
    

    在.m文件中,出了实现这几个初始化方法之外,还需额外实现几个方法。
    以下是.m文件的具体实现,其中类似于这种方法都可以根据自身需求进行调整。

    - (id)modelByIndex:(NSIndexPath *)indexPath 
    
    //
    //  DataSource.m
    //  CustomDataSourceAndDelegate
    //
    //  Created by zjl on 2017/8/9.
    //  Copyright © 2017年 zjlzjl. All rights reserved.
    //
    
    #import "DataSource.h"
    @interface DataSource(){
        CellIDConfigureBlock _cellIDConfigureBlock;
        CellConfigureBlock _cellConfigureBlock;
        ReusableViewIDConfigureBlock _reusableViewIDConfigureBlock;
        ReusableViewConfigureBlock _reusableViewConfigureBlock;
    }
    
    @end
    @implementation DataSource
    - (instancetype)initWithDataArray:(NSArray *)dataArray
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock {
    
        return [self initWithDataArray:dataArray numberOfSection:1 cellIDConfigureBlock:cellIDConfigureBlock cellConfigure:cellConfigureBlock];
    }
    
    - (instancetype)initWithDataArray:(NSArray *)dataArray
                      numberOfSection:(NSInteger)numberOfSection
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock {
        return [self initWithDataArray:dataArray numberOfSection:numberOfSection cellIDConfigureBlock:cellIDConfigureBlock cellConfigure:cellConfigureBlock ReusableViewIDConfigureBlock:nil ReusableViewConfigureBlock:nil];
    }
    
    - (instancetype)initWithDataArray:(NSArray *)dataArray
                      numberOfSection:(NSInteger)numberOfSection
                 cellIDConfigureBlock:(CellIDConfigureBlock)cellIDConfigureBlock
                        cellConfigure:(CellConfigureBlock)cellConfigureBlock
         ReusableViewIDConfigureBlock:(ReusableViewIDConfigureBlock)reusableViewIDConfigureBlock
           ReusableViewConfigureBlock:(ReusableViewConfigureBlock)reusableViewConfigureBlock {
        self = [super init];
        if (self) {
            _dataArray = dataArray;
            _cellIDConfigureBlock = cellIDConfigureBlock;
            _cellConfigureBlock = cellConfigureBlock;
            _numberOfSection = numberOfSection;
            _reusableViewIDConfigureBlock = reusableViewIDConfigureBlock;
            _reusableViewConfigureBlock = reusableViewConfigureBlock;
        }
        return self;
    }
    
    - (void)setDataArray:(NSArray *)dataArray {
        _dataArray = dataArray;
        
    }
    
    - (id)modelByIndex:(NSIndexPath *)indexPath {
        if (_numberOfSection == 1 && ![_dataArray[indexPath.section] isKindOfClass:[NSArray class]]) {
            return _dataArray[indexPath.row];
        }else {
    //        NSLog(@"section=%ld",(long)indexPath.section);
    //        NSLog(@"row=%ld",(long)indexPath.row);
            return _dataArray[indexPath.section][indexPath.row];
        }
    }
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return _numberOfSection;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if (_numberOfSection == 1 && ![_dataArray[section] isKindOfClass:[NSArray class]]) {
            return [self.dataArray count];
        }else {
            return [_dataArray[section] count];
        }
        
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        id model = [self modelByIndex:indexPath];
        NSString *cellIdentifier = _cellIDConfigureBlock(indexPath,model);
        id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if ([cell conformsToProtocol:@protocol(ConfigureCellDelegate)]) {
            [cell configureCellWithModel:model];
        }
        _cellConfigureBlock(indexPath,model,cell);
        return cell;
    }
    
    
    #pragma mark - UICollectionViewDataSource
    - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
        return _numberOfSection;
    }
    
    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
        if (_numberOfSection == 1 && ![_dataArray[section] isKindOfClass:[NSArray class]]) {
            return [self.dataArray count];
        }else {
            return [_dataArray[section] count];
        }
    }
    
    - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        id model = [self modelByIndex:indexPath];
        NSString *cellIdentifier = _cellIDConfigureBlock(indexPath,model);
        id cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        _cellConfigureBlock(indexPath,model,cell);
        if ([cell conformsToProtocol:@protocol(ConfigureCellDelegate)]) {
            [cell configureCellWithModel:model];
        }
    
        return cell;
    }
    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
        UICollectionReusableView *view = nil;
        if (_reusableViewIDConfigureBlock) {
            NSDictionary *reusableViewIDDict = _reusableViewIDConfigureBlock(indexPath);
            NSString *reusableViewID = [reusableViewIDDict objectForKey:kind];
    
    //        UIView *customView = reusableViewDict[kind];
    
            if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
                view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reusableViewID forIndexPath:indexPath];
            }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
                view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:reusableViewID forIndexPath:indexPath];
            }
            _reusableViewConfigureBlock(indexPath,view,kind);
    //        [view addSubview:customView];
        }
        return view;
    }
    @end
    
    

    配置delegate

    配置Delegate的方法和DataSource类似,这里就不一一解释了,有兴趣可以去github查看详细的代码。链接在最后会贴上。

    调用方式

    我的调用方式使用了MVVM的架构方式,仅供参考,也可以根据你自己的框架进行调整,下面给出我的调用方法。
    以UITableView为例。
    初始化UITableView

    tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
    [self.view addSubview:tableview];
    

    初始化数据源,每一个cell对应一个model

    dataArray = [[NSMutableArray alloc] init];
    FirstModel *fm1 = [[FirstModel alloc] init];
    fm1.isRed = YES;
    FirstModel *fm2 = [[FirstModel alloc] init];
    [dataArray addObject:@[fm1]];
    [dataArray addObject:@[fm2]];
    

    注册UITableViewCell

    [tableview registerClass:[FirstTableViewCell class] forCellReuseIdentifier:@"firstcell"];
    

    初始化DataSource

        dataSource = [[CustomTableViewDataSource alloc] initWithDataArray:dataArray numberOfSection:[dataArray count] cellIDConfigureBlock:^NSString *(NSIndexPath *indexPath, id model) {
            return @"firstcell";
            
        } cellConfigure:^(NSIndexPath *indexPath, id model, id cell) {
            if ([cell isKindOfClass:[FirstTableViewCell class]]) {
                FirstTableViewCell *fcell = (FirstTableViewCell *)cell;
                fcell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
        }];
        tableview.dataSource = dataSource;
    

    以上就是在viewcontroller中所需的代码。剩下的就是在UITableViewCell中配置cell,即可完成TableView的实现。
    在cell中,只要实现ConfigureCellDelegate协议中的方法,就能拿到dataArray中配置的model,来配置cell的显示。

    //
    //  FirstTableViewCell.h
    //  CustomDataSourceAndDelegate
    //
    //  Created by zjl on 2017/8/9.
    //  Copyright © 2017年 zjlzjl. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    #import "DataSource.h"
    
    @interface FirstTableViewCell : UITableViewCell<ConfigureCellDelegate>
    
    @end
    
    
    //
    //  FirstTableViewCell.m
    //  CustomDataSourceAndDelegate
    //
    //  Created by zjl on 2017/8/9.
    //  Copyright © 2017年 zjlzjl. All rights reserved.
    //
    
    #import "FirstTableViewCell.h"
    #import "FirstModel.h"
    
    @implementation FirstTableViewCell
    
    - (void)awakeFromNib {
        [super awakeFromNib];
        // Initialization code
    }
    
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
        [super setSelected:selected animated:animated];
    
        // Configure the view for the selected state
    }
    
    
    #pragma mark - ConfigureCellDelegate
    - (void)configureCellWithModel:(id)model {
        FirstModel *fm = (FirstModel *)model;
        
        if (fm.isRed) {
            self.backgroundColor = [UIColor redColor];
        }else {
            self.backgroundColor = [UIColor yellowColor];
        }
    }
    @end
    
    

    总结

    通过这种实现方式,能够大幅度的给ViewController减负,也能减少我们编写Tableview和CollectionView的代码量,提高效率。具体更多的用法可以参考我github中的example文件夹中的例子,有多种实现方式,包括每行单独定义等等功能。https://github.com/zjl0624/CustomDataSourceAndDelegate

    相关文章

      网友评论

          本文标题:一种把UITableView,UICollectionView的

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