免费开源的iOS开发学习平台

UITableView详解:14-UITableView+FDTemplateLayoutCell计算Cell高度

使用 UITableView+FDTemplateLayoutCell 无疑是解决单元格高度计算问题的最佳实践之一,既有 iOS8 self-sizing 功能简单的 API,又可以达到 iOS7 流畅的滑动效果,还保持了最低支持 iOS6。

SDK的下载与导入

  • 登录GitHub下载第三方库UITableView+FDTemplateLayoutCell。

https://github.com/forkingdog/UITableView-FDTemplateLayoutCell

  • 解压后,将图中Classes文件夹拖入到项目中。

  • 弹出如下提示框,选中第1、3、4项,点击finish。

使用方法

当使用UITableView+FDTemplateLayoutCell框架时,有3个使用步骤。

  • 使用自动布局为单元格中的子控件添加完整的边界约束("top", "left", "bottom", "right")

  • 当使用dequeueReusableCellWithIdentifier:方法从缓存池中查找单元格对象之前,需要提前注册单元格,单元格的注册方法有如下两个,分别对应使用代码以及Xib创建单元格

- (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier;
  • 在tableView:heightForRowAtIndexPath:方法中,调用UITableView+FDTemplateLayoutCell中的fd_heightForCellWithIdentifier:configuration:方法,即可实现单元格的动态高度调整
- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration;
#import "UITableView+FDTemplateLayoutCell.h"

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"reuse identifer" configuration:^(id cell) {
        // 如在tableView:cellForRowAtIndexPath:方法中为单元格设置数据时做相同操作,例如:
        //    cell.entity = self.feedEntities[indexPath.row];
    }];
}

示例代码

下方的示例代码,演示了使用UITableView+FDTemplateLayoutCell框架中的方法来动态实现单元格高度的动态调整的核心代码。

  • 创建MYTableViewCell类,创建对应的xib文件,并对其中的子控件设置约束关系

  • 在创建表视图UITableView对象时,调用registerNib:forCellReuseIdentifier:注册单元格
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStyleGrouped];
        //设置代理和数据源
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //注册单元格
         [_tableView registerNib:[UINib nibWithNibName:@"MYTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellId"];
    }
    return _tableView;
}
  • 在tableView:heightForRowAtIndexPath:方法中设置每个单元格的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [_tableView fd_heightForCellWithIdentifier:@"cellId" configuration:^(MYTableViewCell *cell) {
        [cell setCellData:self.array[indexPath.row]];
    }];
}

运行结果如下。本案例的完整代码,请读者到网站下载。

示例代码

https://github.com/99ios/8.2.14