UITableViewCell自适应高度

来源:互联网 发布:在淘宝买摩托车可靠吗 编辑:程序博客网 时间:2024/04/30 06:53

在网上看见一个开源的扩展,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
原创粉丝点击