# HYTableViewSection **Repository Path**: Ianhwu/HYTableViewSection ## Basic Information - **Project Name**: HYTableViewSection - **Description**: 具体使用参考 - **Primary Language**: Objective-C - **License**: MIT - **Default Branch**: master - **Homepage**: https://yansaid.github.io/2017/05/09/uitableview%20解耦/ - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-05-09 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # HYTableViewSection HYTableViewSection is for using model to make styles. ## Install pod 'HYTableViewSection' ## Usage 产品开发的时候无法避免的就是在一个 UITableView中, 包含多种样式的 cell, 我们通常的做法如下: ``` if (indexPath.row == 0) { } else if (indexPath.row == 1) { } else if (indexPath.row == 2) { } ..... ``` 这样的做法没有问题, 但是如果有很多种 cell 的话, 例如资料页, 当需要在第二和第三个 cell 之间插入一个 cell 的时候, 我们需要把数组添加一列, 然后把整个 if 改一遍, 如何避免 index 之间的耦合? OK, 简单来说就是在数据模型 中添加一个标识, 数据的排列交给数组, 我们不判断当前是第几个, 只根据标识来确定放那种样式的cell, 这样只有当增加新的样式的时候才会涉及到改 UI 部分的代码, 大部分情况我们只需要对数组进行排序即可, 而不必因为该数组, 从而再改 if. ``` - (void)reload { int i = 0; while (i < 5) { i++; HYTableViewRow *row = [HYTableViewRow row:@{@"title":@"style1"}]; row.identifier = @"style1"; row.heightBlock = ^CGFloat{ return 100; }; [self.tableView.hy_section addRowModel:row atSection:0]; } HYTableViewRow *row1 = [HYTableViewRow row:@{@"title":@"style2"}]; row1.identifier = @"style2"; row1.heightBlock = ^CGFloat{ return 100; }; [self.tableView.hy_section addRowModel:row1 atSection:1]; HYTableViewRow *row2 = [HYTableViewRow row:nil]; row2.identifier = @"style2"; [self.tableView.hy_section addRowModel:row2 atSection:2]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { HYTableViewRow *row = [self.tableView.hy_section modelAtIndexPath:indexPath]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:row.identifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:row.identifier]; } cell.textLabel.text = row.model[@"title"]; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { HYTableViewRow *row = [self.tableView.hy_section modelAtIndexPath:indexPath]; return row.height; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.tableView.hy_section numberOfRowsInSection:section]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.tableView.hy_section numberOfSections]; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 50; } ``` ## License HYTableViewSection is available under the MIT license. See the LICENSE file for more info.