
項目地址:https://github.com/chentoo/AITableView
CocoaPods:pod 'AITableView'
這是一次「簡化 UITableView 使用方式」的嘗試。用起來不用再實現那一大堆 delegate 與 datasource 方法,也不用在 cellForRow 裡堆滿 if else / switch,只需要一段簡單的配置過程,就能輕鬆完成列表的搭建與佈局。
它借鑑了 MVVM 思想,最終拼裝成列表的不再是一個個 cell,而是一個個輕量的 ViewModel(暫且稱作 CellModel)。每個 CellModel 唯一對應一種 cell,只持有屬性,而每個屬性都直接決定 cell 的展示效果。
從長遠看,你可以積累一套自己的 CellModel 庫。無論是同一個列表在不同業務分支下的展示差異,還是完全不同的列表,都可以按需求挑出合適的 CellModel、配置屬性、拼裝即可。
接入時不需要修改原有 cell 與 model 的基類,只需按需要實現相應協議。
把所有 UI 配置集中在 - (void)AIConfigureWithModel: 中,並在類方法 + (CGFloat)AIHeightWithModel: 裡返回行高。
#import "DemoTableViewNameCell.h"
#import "AITableViewProtocal.h"
#import "DemoNameCellModel.h"
@interface DemoTableViewNameCell ()
@property (nonatomic, strong) UILabel *nameLabel;
@end
@implementation DemoTableViewNameCell
#pragma mark - AITableViewCellProtocal
- (void)AIConfigureWithModel:(DemoNameCellModel *)model {
self.nameLabel.text = model.name;
}
+ (CGFloat)AIHeightWithModel:(id)model {
return 30.0f;
}
@endCellModel 可以繼承任意基類,也不需要實現任何協議,唯一的硬性要求是:cell 能夠僅依賴它所對應的 CellModel 完成全部配置。特別注意,CellModel 與 Cell 是一一對應的關係,不同的 Cell 類不能共用同一個 CellModel。
// AITableView.h - (void)bindModelClass:(Class)modelClass withCellClass:(Class)cellClass; - (void)bindModelClass:(Class)modelClass withCellNibClass:(Class)cellNibClass;
如果某個 cell 的展示完全靜態、不隨外部數據變化,也可以不做 CellModel,直接用靜態綁定:
- (void)bindStaticCellWithCellClass:(Class)cellClass; - (void)bindStaticCellWithCellNibClass:(Class)cellNibClass;
不過從長期維護 CellModel 庫的角度看,為每個 cell 保留一個唯一 CellModel 反而更好管理,因此並不特別推薦靜態綁定。
[self.tableview updateTabelViewWithModels:@[model, sModel, sModel, model]];
需要分區或添加 header / footer 時,用 AITableViewSection 來組織:
@interface AITableViewSection : NSObject
@property (strong, nonatomic) id headerModel;
@property (strong, nonatomic) id footerModel;
@property (strong, nonatomic) NSArray *cellModels;
+ (instancetype)sectionWithHeaderModel:(id)sectionHeaderModel
footerModel:(id)sectionFooterModel
cellModels:(NSArray *)cellModels;
@end[self.tableview updateTableViewWithSections:@[aiSection, aiSection, aiSection]];
更多用法請參考完整示例代碼。
提供了三種方式,可按場景選擇:
AITableView 的 delegate
AITableView 的 block
CellModel 上的協議 block(這種方式的好處是可以把回調直接配置在 model 身上,與數據放在一起)
具體用法請看示例代碼。