? ? iOS界面開發(fā)中,每個控制器中重復度最高的代碼砰识,可能就是 TableView 的相關方法了慎菲。
- (NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section;
-?(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath;
-?(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath;
? ? 上面的代碼在項目中大量出現(xiàn)辩诞,Table View 通過這些數(shù)據(jù)源方法和代理方法與 view controllers 之間傳遞信息,而幾乎所有的任務都在 view controller 中進行酒朵。為了避免讓 view controllers 做所有的事桦锄,我們可以將所有的這些繁瑣的任務,交給一個專門的類來處理蔫耽,view controllers 只需在 viewDidLoad: 中告訴這個類要做什么结耀。基于這個思路,我對 Table View / Collection View 的數(shù)據(jù)源和代理方法進行了封裝图甜。
? ? 在MVC模式下碍粥,每個 Cell 應該有一個對應的 Model 來處理數(shù)據(jù)業(yè)務,在初始化 WFDataSource 時黑毅,需要傳入Model與Cell的對應關系嚼摩。通過block回調,將 cell 與 model 對應起來矿瘦。
NSDictionary*modelCellMap = @{@"DemoCellModel":@"DemoCell",@"DemoCellModel_XIB":@"DemoCell_XIB",};
WFDataSource*dataSource = [[WFDataSourcealloc]initWithModelCellMap:modelCellMapcellConfigBlock:^(idcell,iditem,NSIndexPath*indexPath) {
[cellconfigCellWithItem:item];}
];
? ? 在日常開發(fā)中枕面,往往會出現(xiàn)使用XIB創(chuàng)建的Cell和純代碼Cell混用的情形,而兩者在通過 table view 的緩存池機制創(chuàng)建 cell 時的差異缚去,可以通過下面兩個方法進行統(tǒng)一膊畴。
- (void)registerNib:(nullableUINib*)nibforCellReuseIdentifier:(NSString*)identifier;
-?(void)registerClass:(nullable?Class)cellClassforCellReuseIdentifier:(NSString*)identifier;
? ? WFDataSource 對此進行了處理, 傳入的cell 支持任意方式創(chuàng)建,并可以混用病游。
? ? Table View 的其他數(shù)據(jù)源方法和代理方法,通過 block 的方式扁平化處理稠通。
dataSource.headerViewForSection= ^UIView*(idsectionItem, NSInteger section) {
? ? //create?headerView
? ? returnheaderView;
};
dataSource.didSelectCellBlock= ^(iditem,NSIndexPath*indexPath) {
};
dataSource.heightForRow= ^CGFloat (iditem,NSIndexPath*indexPath) {
? ? //height?for?different?cell
? ? returnheight;
};
? ? dataSource 創(chuàng)建后衬衬,需要將綁定的 table view 賦給它。
self.dataSource.tableView=self.tableView;
? ? 項目已經開源改橘,更多用法滋尉,可以參考項目Demo。 https://github.com/jwfstars/WFDataSource