UITableView中有很多情况下cell的高度是不固定的,这时候cell的高度取决于内容的多少,今天介绍几个方法来达到自定义非等高cell的效果。
LMTestCell.h中加入方法:
/** 返回cell 高度*/
-(CGFloat)cellHeight;
LMTestCell.m中对应方法:
-(CGFloat)cellHeight
{
if (self.pictureView.hidden) {
return CGRectGetMaxY(self.contentLabel.frame)+10;
}else
{
return CGRectGetMaxY(self.pictureView.frame)+10;
}
}
ViewController.m中对应方法:
#import "ViewController.h"
#import "LMTestCell.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
UITableView *_weiboTableView;
}
/* 存放所有cell的高度 */
@property(nonatomic,strong)NSMutableDictionary *hegihts;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
_weiboTableView = tableView;
_weiboTableView.delegate = self;
_weiboTableView.dataSource = self;
[self.view addSubview:_weiboTableView];
}
-(NSMutableDictionary *)hegihts
{
if (!_hegihts) {
_hegihts = [NSMutableDictionary dictionary];
}
return _hegihts;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
LMTestCell *cell = [LMTestCell cellWithTableView:tableView];
[cell setContent:indexPath.row];
NSLog(@"%zd",cell.cellHeight);
//存储高度
self.hegihts[@(indexPath.row)] = @(cell.cellHeight);
return cell;
}
#pragma mark - 01-自定义非等高cell-重复高,效率低
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
// LMTestCell *cell = [LMTestCell cellWithTableView:tableView];
// [cell setContent:indexPath.row];
// //强制布局
// [cell layoutIfNeeded];
// return cell.cellHeight;
//}
#pragma mark - 02-自定义非等高cell
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cellForRowAtIndexPath:获取已经在tableivew中显示的cell。
CGFloat height = [self.hegihts[@(indexPath.row)] floatValue];
return height;
}
/**
返回每一行的估计高度
只返回了估计高度,那么就会先调用tableView:cellForRowIndexPath:方法创建cell,在调用tableView heightForRowAtIndexPath:方法获取cell的真实高度。
*/
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 250;
}
@end