曾经和一些朋友和同学聊过 UITableView 在项目中的运用,发现大部分小伙伴和我之前一样,都是按照标准的流程,在 ViewController 里准守UITableViewDataSource 和 UITableViewDelegate 协议。然后完成代理需要完成的一系列方法。
UITableView 是在项目中很常见的一个控件,因此也就意味着你要重复的写这样相同的代码。当然,有很多选择了使用自定义代码块,解决了重复写相同代码的弊端。但对于整个项目来说,重复的代码还是显得过于臃肿。这里就分享一下另一种解决方案,分离 UITableView 的 Delegate 和 Datasource。
既然要分离,那么我们需要创建继承与 NSObject 的两个类,分别准守UITableViewDataSource 和 UITableViewDelegate 协议。
TBDataSource
.h
#import <UIKit/UIKit.h>
// cell 赋值的 block
typedef void (^TBCellConfigBlock)(UITableViewCell *targetCell, id data, NSInteger row);
@interface TBDataSource : NSObject<UITableViewDataSource>
@property (nonatomic, strong) NSArray *listData;//数据源
@property (nonatomic, strong) NSString *tableCellIdentifier;// cell 复用标识
@property (nonatomic, copy) TBCellConfigBlock tableCellConfigBlock;
@end
.m
#impor