TemplateScrolls 提供了兩個(gè)視圖類 TTTableView 和 TTCollectionView,支持快速搭建 TableView 和 CollectionView.
它的便捷之處有
- 省去了所有的 dataSource 和 delegate 的代理方法,只需要少量的列表配置。
- 所得即所見,只要配置發(fā)生變化,列表會(huì)自動(dòng)進(jìn)行局部刷新。
- 不用關(guān)心視圖重用 (identifier) 的細(xì)節(jié)
- Cell、Header、Footer 統(tǒng)一的代碼風(fēng)格
以 TTTableView 為例
1. 創(chuàng)建自定義 Cell、Header、Footer
繼承 TTTableViewCell、 TTTableReusableView,創(chuàng)建自定義的可復(fù)用視圖類
@interface TTMessageCell : TTTableViewCell ...
@implementation TTMessageCell
// - init {} // 不需要實(shí)現(xiàn) init 方法
// 在這里搭建你的 UI 視圖層級(jí)結(jié)構(gòu)
- (void)makeSubview { }
// 在這里為所有子視圖創(chuàng)建約束
- (void)makeConstraint { }
// 使用 data 填充到視圖上
- (void)refreshView:(TTMessageModel *)data { }
@end
// 與 Cell 相同,完全一樣的代碼結(jié)構(gòu)
@interface TTMessageHeader : TTTableReusableView ...
@implementation TTMessageHeader
- (void)makeSubview { }
- (void)makeConstraint { }
- (void)refreshView:(NSString *)data { }
@end
2. 配置列表
Cell 和 Header/Footer 的配置分別是 TTCellTemplate,TTReusableViewTemplate,它們都屬于 View 的配置,有兩個(gè)重要的屬性 viewClass 和 data,表示指定視圖的類型,以及要展示的數(shù)據(jù)
Section 的配置是 TTSectionTemplate,主要是存儲(chǔ)著 cells、header、footer 的配置
TTSectionTemplate *section = [TTSectionTemplate new];
section.header.viewClass = [TTMessageHeader class];
section.header.data = @"2021-02-09";
// section.footer // 沒有 footer 不需要配置
[dataArray enumerateObjectsUsingBlock:^(TTMessageModel *data, NSUInteger idx, BOOL *stop) {
TTCellTemplate *cell = [TTCellTemplate new];
cell.viewClass = [TTMessageCell class];
cell.data = data;
// 如果 cell 可以用約束自動(dòng)撐開,這里可以不指定高度
// cell.height = custom compute height with data
[section.cells addObject:cell];
}];
3. 裝入配置到 sections
TTTableView 的屬性 sections,是一個(gè)數(shù)組,只需要將配置好的 sections 添加到里面即可
@property (nonatomic, readonly) TTTableView *tableView;
TTSectionTemplate *section = ......
[self.tableView.sections addObject:section];
如此, TableView 就快速的渲染出來了
4. CollectionView
類似的,如果你要開發(fā)一個(gè)CollectionView,也是一樣的步驟
- 繼承 TTCollectionViewCell, TTCollectionReusableView
- 配置 TTCellTemplate, TTSectionTemplate
- 對(duì) TTCollectionView.sections 進(jìn)行添加、替換、插入等操作
Demo 見 這里