UITableViewCell自适应高度

在网上看见一个开源的扩展,UITableView+FDTemplateLayoutCell,让高度计算这个事情变的前所未有的简单。

UITableView 询问 cell 高度有两种方式。

1.针对所有 Cell 具有固定高度的情况

1
self.tableView.rowHeight = 88;

对于定高需求的表格,强烈建议使用这种(而非下面的)方式保证不必要的高度计算和调用。

2.实现 UITableViewDelegate 代理方法:

1
2
3
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     // return xxx
}

需要注意的是,实现了这个方法后,rowHeight 的设置将无效。所以,这个方法适用于具有多种 cell 高度的 UITableView。

这些方法做不到根据内容多少来自适应cell高度。

下面将介绍UITableView+FDTemplateLayoutCell如何实现cell自适应,使用极其简单

步骤:

自己建一个tableView控件,我这里使用了prototypeCells



demo代码如下:

#import "ViewController.h"
#import "DataCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
@interface ViewController ()
{
        NSArray *array;

}
@property (nonatomic, assign) BOOL cellHeightCacheEnabled;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mytableview.fd_debugLogEnabled = YES;
    array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"PropertyList.plist" ofType:nil]];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 return [tableView fd_heightForCellWithIdentifier:@"hellocell" configuration:^(DataCell *cell) {
     cell.name.text = [[array objectAtIndex:indexPath.row] objectForKey:@"name"];
     cell.content.text = [[array objectAtIndex:indexPath.row] objectForKey:@"content"];
 }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = [array objectAtIndex:indexPath.row];
    DataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hellocell" forIndexPath:indexPath];
    cell.name.text = [dict objectForKey:@"name"];
    cell.content.text = [dict objectForKey:@"content"];
    return cell;
}

@end

唯一需要注意的地方就是cell重用的那个id必须是已经被注册过得,也就是我们前面prototypeCells里面的ID;

下面分享UITableView+FDTemplateLayoutCell的类文件:https://github.com/forkingdog/UITableView-FDTemplateLayoutCell


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值