自定义非等高cell01-xib

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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值